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,
|
||||
})
|
||||
}
|
||||
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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=
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+8832
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,138 @@
|
||||
app_id,name,currency,initial,final,discount_pct,lowest_price,lowest_date,max_discount_pct,times_discounted
|
||||
3590,Plants vs. Zombies GOTY Edition,EUR,4.99,4.99,0,0.99,2016-10-28 (USD),,
|
||||
12210,Grand Theft Auto IV: The Complete Edition,EUR,19.99,5.99,70,5.99,2020-11-25 (USD),,
|
||||
72850,The Elder Scrolls V: Skyrim,EUR,14.99,14.99,0,,,,
|
||||
203160,Tomb Raider Game of the Year,EUR,19.99,19.99,0,1.99,2026-10-23 (USD),,
|
||||
203770,Crusader Kings II,,,,0,,,,
|
||||
208650,Batman™: Arkham Knight,EUR,19.99,19.99,0,1.99,2024-06-27 (USD),,
|
||||
214950,Total War: ROME II - Emperor Edition,EUR,29.99,7.49,75,5.99,2024-11-27 (USD),,
|
||||
218620,PAYDAY 2,EUR,9.49,9.49,0,0.99,2019-12-19 (USD),,
|
||||
219990,Grim Dawn,EUR,25.99,5.19,80,2.49,2024-12-19 (USD),,
|
||||
233860,Kenshi,EUR,26.99,26.99,0,8.39,2026-05-25 (USD),,
|
||||
239140,Dying Light,EUR,24.99,24.99,0,2.49,2026-03-19 (USD),,
|
||||
251570,7 Days to Die,EUR,43.99,43.99,0,5.99,2022-12-23 (USD),,
|
||||
268910,Cuphead,EUR,19.99,19.99,0,6.15,2019-12-26 (USD),,
|
||||
270880,American Truck Simulator,EUR,19.99,4.99,75,1.99,2024-06-27 (USD),,
|
||||
275850,No Man's Sky,EUR,58.99,58.99,0,15.49,2019-12-26 (USD),,
|
||||
291550,Brawlhalla,,,,0,,,,
|
||||
304930,Unturned,,,,0,,,,
|
||||
305620,The Long Dark,EUR,16.99,16.99,0,3.49,2025-04-24 (USD),,
|
||||
306130,The Elder Scrolls® Online,EUR,19.99,19.99,0,1.99,2025-03-13 (USD),,
|
||||
346110,ARK: Survival Evolved,EUR,14.79,14.79,0,4.49,2025-06-05 (USD),,
|
||||
363970,Clicker Heroes,,,,0,,,,
|
||||
367520,Hollow Knight,EUR,14.79,14.79,0,2.99,2024-04-11 (USD),,
|
||||
386360,SMITE®,,,,0,,,,
|
||||
387990,Scrap Mechanic,EUR,28.99,28.99,0,11.99,2017-06-22 (USD),,
|
||||
418370,Resident Evil 7 Biohazard,EUR,19.99,19.99,0,3.99,2023-12-21 (USD),,
|
||||
431730,Aseprite,EUR,20.49,20.49,0,,,,
|
||||
444200,World of Tanks Blitz,,,,0,,,,
|
||||
477160,Human Fall Flat,EUR,19.99,19.99,0,1.99,2021-10-25 (USD),,
|
||||
527230,For The King,EUR,19.99,1.99,90,1.99,2021-10-25 (USD),,
|
||||
529340,Victoria 3,EUR,49.99,49.99,0,11.99,2024-05-09 (USD),,
|
||||
548430,Deep Rock Galactic,EUR,29.99,29.99,0,8.1,2026-10-01 (USD),,
|
||||
582660,Black Desert,EUR,9.99,0.99,90,0.99,2025-02-19 (USD),,
|
||||
594650,Hunt: Showdown 1896,EUR,29.99,29.99,0,10.76,2026-09-17 (USD),,
|
||||
632360,Risk of Rain 2,EUR,24.99,24.99,0,4.99,2026-01-30 (USD),,
|
||||
644930,They Are Billions,EUR,29.99,29.99,0,18.74,2018-05-05 (USD),,
|
||||
646570,Slay the Spire,EUR,22.99,22.99,0,2.49,2025-12-18 (USD),,
|
||||
648800,Raft,EUR,20.49,20.49,0,9.99,2024-05-02 (USD),,
|
||||
700330,SCP: Secret Laboratory,,,,0,,,,
|
||||
714010,Aimlabs,,,,0,,,,
|
||||
739630,Phasmophobia,EUR,18.99,18.99,0,10.49,2024-06-27 (USD),,
|
||||
744900,Dead Frontier 2,,,,0,,,,
|
||||
750920,Shadow of the Tomb Raider: Definitive Edition,EUR,39.99,39.99,0,3.95,2026-10-23 (USD),,
|
||||
761890,Albion Online,,,,0,,,,
|
||||
779340,Total War: THREE KINGDOMS,EUR,39.99,11.99,70,7.59,2026-05-18 (USD),,
|
||||
883710,Resident Evil 2,EUR,39.99,39.99,0,,,,
|
||||
960090,Bloons TD 6,EUR,13.79,13.79,0,,,,
|
||||
960170,DJMAX RESPECT V,EUR,41.99,41.99,0,,,,
|
||||
976730,Halo: The Master Chief Collection,EUR,39.99,39.99,0,,,,
|
||||
977400,Cell to Singularity - Evolution Never Ends,,,,0,,,,
|
||||
990080,Hogwarts Legacy,EUR,59.99,59.99,0,,,,
|
||||
1057090,Ori and the Will of the Wisps,EUR,29.99,29.99,0,,,,
|
||||
1062090,Timberborn,EUR,33.99,33.99,0,,,,
|
||||
1118200,People Playground,EUR,8.19,8.19,0,,,,
|
||||
1149460,ICARUS,EUR,36.99,36.99,0,,,,
|
||||
1151340,Fallout 76,EUR,39.99,39.99,0,,,,
|
||||
1167630,Teardown,EUR,29.99,29.99,0,,,,
|
||||
1222140,Detroit: Become Human,EUR,39.99,39.99,0,,,,
|
||||
1256670,Library Of Ruina,EUR,24.99,24.99,0,,,,
|
||||
1258080,Shop Titans,,,,0,,,,
|
||||
1260320,Party Animals,EUR,17.99,17.99,0,,,,
|
||||
1267910,Melvor Idle,EUR,9.75,9.75,0,,,,
|
||||
1282270,Strinova,,,,0,,,,
|
||||
1293830,Forza Horizon 4,,,,0,,,,
|
||||
1295660,Sid Meier's Civilization VII,EUR,69.99,69.99,0,,,,
|
||||
1304930,The Outlast Trials,EUR,38.99,38.99,0,,,,
|
||||
1326470,Sons Of The Forest,EUR,28.99,28.99,0,,,,
|
||||
1353300,Idle Slayer,,,,0,,,,
|
||||
1361210,"Warhammer 40,000: Darktide",EUR,39.99,39.99,0,,,,
|
||||
1366540,Dyson Sphere Program,EUR,16.79,16.79,0,,,,
|
||||
1407200,World of Tanks,,,,0,,,,
|
||||
1426210,It Takes Two,EUR,39.99,39.99,0,,,,
|
||||
1551360,Forza Horizon 5,EUR,59.99,59.99,0,,,,
|
||||
1566200,Tape to Tape,EUR,19.5,19.5,0,,,,
|
||||
1599340,Lost Ark,,,,0,,,,
|
||||
1617400,The Bazaar,,,,0,,,,
|
||||
1643320,S.T.A.L.K.E.R. 2: Heart of Chornobyl,EUR,59.99,59.99,0,,,,
|
||||
1659040,HITMAN World of Assassination,EUR,69.99,27.99,60,,,,
|
||||
1677280,Company of Heroes 3,EUR,54.99,18.14,67,,,,
|
||||
1687950,Persona 5 Royal,EUR,59.99,17.99,70,,,,
|
||||
1778820,TEKKEN 8,EUR,49.99,27.49,45,,,,
|
||||
1868140,DAVE THE DIVER,EUR,19.99,19.99,0,,,,
|
||||
1920960,VPet-Simulator,,,,0,,,,
|
||||
2001120,Split Fiction,EUR,49.99,49.99,0,,,,
|
||||
2054970,Dragon's Dogma 2,EUR,39.99,39.99,0,,,,
|
||||
2113850,Spirit City: Lofi Sessions,EUR,11.79,11.79,0,,,,
|
||||
2116120,Incursion Red River,EUR,21.56,21.56,0,,,,
|
||||
2139460,Once Human,,,,0,,,,
|
||||
2223980,Nomad Drive,EUR,14.49,14.49,0,,,,
|
||||
2250040,Crosshair V2,,,,0,,,,
|
||||
2288340,ACE COMBAT 8: WINGS OF THEVE,EUR,69.99,69.99,0,,,,
|
||||
2300320,Farming Simulator 25,EUR,29.99,29.99,0,,,,
|
||||
2320980,Loftia,EUR,28.99,28.99,0,,,,
|
||||
2333000,Silver Pines,EUR,24.99,24.99,0,,,,
|
||||
2338770,NBA 2K24,,,,0,,,,
|
||||
2379780,Balatro,EUR,13.99,13.99,0,,,,
|
||||
2426960,Summoners War,,,,0,,,,
|
||||
2471100,Unnamed Space Idle,,,,0,,,,
|
||||
2479810,Gray Zone Warfare,EUR,39.99,39.99,0,,,,
|
||||
2537590,Microsoft Flight Simulator 2024,EUR,79.99,79.99,0,,,,
|
||||
2646460,Soulmask,EUR,29.99,29.99,0,,,,
|
||||
2651280,Marvel's Spider-Man 2,EUR,59.99,59.99,0,,,,
|
||||
2661300,Grounded 2,EUR,29.99,29.99,0,,,,
|
||||
2707930,Palia,,,,0,,,,
|
||||
2709570,Supermarket Together,,,,0,,,,
|
||||
2835570,Buckshot Roulette,EUR,2.99,2.99,0,,,,
|
||||
2887580,Active Matter,EUR,29.99,29.99,0,,,,
|
||||
2923300,Banana,,,,0,,,,
|
||||
2929250,over the hill,EUR,24.99,24.99,0,,,,
|
||||
3024040,Stronghold Crusader: Definitive Edition,EUR,19.99,19.99,0,,,,
|
||||
3024130,PAO PAO,EUR,14.99,14.99,0,,,,
|
||||
3052450,Morimens,,,,0,,,,
|
||||
3065800,Marathon,EUR,59.99,26.99,55,,,,
|
||||
3164330,Infinity Nikki,,,,0,,,,
|
||||
3219030,Planet Zoo 2,EUR,49.99,49.99,0,,,,
|
||||
3241660,R.E.P.O.,EUR,9.49,9.49,0,,,,
|
||||
3259780,FINAL FANTASY RESONANCE,EUR,49.99,49.99,0,,,,
|
||||
3450310,Europa Universalis V,EUR,59.99,59.99,0,,,,
|
||||
3477300,Scope X,EUR,4.99,4.99,0,,,,
|
||||
3493540,Transport Fever 3,EUR,49.99,49.99,0,,,,
|
||||
3552140,Retro Rewind - Video Store Simulator,EUR,19.9,19.9,0,,,,
|
||||
3564740,Where Winds Meet,,,,0,,,,
|
||||
3659280,Off The Grid,,,,0,,,,
|
||||
3669620,Warhammer Survivors,EUR,7.49,7.49,0,,,,
|
||||
3934250,Village in the Shade,EUR,49.99,49.99,0,,,,
|
||||
4001890,How to Fish,EUR,7.49,7.49,0,,,,
|
||||
4019220,Dressmaker,EUR,15.47,15.47,0,,,,
|
||||
4025700,Heartopia,,,,0,,,,
|
||||
4128580,BidKing,EUR,2.55,2.55,0,,,,
|
||||
4162040,Zenless Zone Zero,,,,0,,,,
|
||||
4368350,Silly Linguine Cat Simulator Deluxe Online,,,,0,,,,
|
||||
4465480,Counter-Strike:Global Offensive,,,,0,,,,
|
||||
4574820,Rejected Draft,EUR,12.99,9.87,24,,,,
|
||||
4740930,Legend of Defenders,EUR,14.0,14.0,0,,,,
|
||||
5019180,Epic Seven,,,,0,,,,
|
||||
5027520,Megastore: Tidy Up Together,EUR,6.15,6.15,0,,,,
|
||||
5185890,Zombies Aren't Real,EUR,8.99,8.09,10,,,,
|
||||
5480890,Mayday Airways Demo,,,,0,,,,
|
||||
|
@@ -0,0 +1,192 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Scan a folder for files named "<steam_app_id>.csv", look each ID up on Steam,
|
||||
and report current price/discount plus price history.
|
||||
|
||||
Usage:
|
||||
python steam_prices.py /path/to/folder
|
||||
ITAD_KEY=yourkey python steam_prices.py /path/to/folder
|
||||
"""
|
||||
import csv
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
COUNTRY = "dk" # Steam region / currency (dk = DKK)
|
||||
ITAD_KEY = os.environ.get("76f40eccf89a67fc2fd656a273e060e3000d5050") # optional, enables full history
|
||||
STEAM_SHOP_ID_ITAD = 61 # Steam's shop id on IsThereAnyDeal
|
||||
DELAY = 1.5 # seconds between apps (Steam rate limits)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers["User-Agent"] = "steam-price-checker/1.0"
|
||||
|
||||
|
||||
def find_ids(folder: Path):
|
||||
ids = []
|
||||
for f in folder.iterdir():
|
||||
m = re.fullmatch(r"(\d+)\.csv", f.name, re.IGNORECASE)
|
||||
if m:
|
||||
ids.append(int(m.group(1)))
|
||||
return sorted(ids)
|
||||
|
||||
|
||||
def steam_current(app_id):
|
||||
"""Current price + discount from the Steam Store API."""
|
||||
r = session.get(
|
||||
"https://store.steampowered.com/api/appdetails",
|
||||
params={"appids": app_id, "cc": COUNTRY, "filters": "basic,price_overview"},
|
||||
timeout=15,
|
||||
)
|
||||
r.raise_for_status()
|
||||
entry = r.json().get(str(app_id), {})
|
||||
if not entry.get("success"):
|
||||
return None
|
||||
data = entry["data"]
|
||||
po = data.get("price_overview")
|
||||
result = {"name": data.get("name", "?")}
|
||||
if po:
|
||||
result.update(
|
||||
currency=po["currency"],
|
||||
initial=po["initial"] / 100,
|
||||
final=po["final"] / 100,
|
||||
discount_pct=po["discount_percent"],
|
||||
)
|
||||
else:
|
||||
result.update(currency="", initial=None, final=None, discount_pct=0) # free / unreleased
|
||||
return result
|
||||
|
||||
|
||||
def itad_history(app_id):
|
||||
"""Full price history for Steam via IsThereAnyDeal. Returns list of dicts."""
|
||||
if not ITAD_KEY:
|
||||
return None
|
||||
base = "https://api.isthereanydeal.com"
|
||||
r = session.get(
|
||||
f"{base}/games/lookup/v1",
|
||||
params={"key": ITAD_KEY, "appid": f"app/{app_id}"},
|
||||
timeout=15,
|
||||
)
|
||||
r.raise_for_status()
|
||||
j = r.json()
|
||||
if not j.get("found"):
|
||||
return []
|
||||
game_id = j["game"]["id"]
|
||||
|
||||
r = session.get(
|
||||
f"{base}/games/history/v2",
|
||||
params={
|
||||
"key": ITAD_KEY,
|
||||
"id": game_id,
|
||||
"country": COUNTRY.upper(),
|
||||
"shops": STEAM_SHOP_ID_ITAD,
|
||||
"since": "2000-01-01T00:00:00Z",
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
out = []
|
||||
for h in r.json():
|
||||
deal = h.get("deal", {})
|
||||
out.append(
|
||||
{
|
||||
"date": h.get("timestamp"),
|
||||
"price": deal.get("price", {}).get("amount"),
|
||||
"regular": deal.get("regular", {}).get("amount"),
|
||||
"cut": deal.get("cut"),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def cheapshark_lowest(app_id):
|
||||
"""Fallback: all-time lowest price (USD) from CheapShark, no key needed."""
|
||||
r = session.get(
|
||||
"https://www.cheapshark.com/api/1.0/games",
|
||||
params={"steamAppID": app_id},
|
||||
timeout=15,
|
||||
)
|
||||
r.raise_for_status()
|
||||
games = r.json()
|
||||
if not games:
|
||||
return None
|
||||
r = session.get(
|
||||
"https://www.cheapshark.com/api/1.0/games",
|
||||
params={"id": games[0]["gameID"]},
|
||||
timeout=15,
|
||||
)
|
||||
r.raise_for_status()
|
||||
low = r.json().get("cheapestPriceEver")
|
||||
if low:
|
||||
return {"price_usd": float(low["price"]), "date": time.strftime("%Y-%m-%d", time.gmtime(low["date"]))}
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
folder = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
|
||||
ids = find_ids(folder)
|
||||
if not ids:
|
||||
print(f"No '<id>.csv' files found in {folder.resolve()}")
|
||||
return
|
||||
print(f"Found {len(ids)} app IDs. History source: {'IsThereAnyDeal' if ITAD_KEY else 'CheapShark (lowest only)'}\n")
|
||||
|
||||
summary_rows = []
|
||||
history_rows = []
|
||||
|
||||
for app_id in ids:
|
||||
try:
|
||||
cur = steam_current(app_id)
|
||||
except requests.RequestException as e:
|
||||
print(f"[{app_id}] Steam lookup failed: {e}")
|
||||
continue
|
||||
if not cur:
|
||||
print(f"[{app_id}] Not found on Steam store")
|
||||
continue
|
||||
|
||||
row = {"app_id": app_id, **cur, "lowest_price": "", "lowest_date": "", "max_discount_pct": "", "times_discounted": ""}
|
||||
|
||||
try:
|
||||
hist = itad_history(app_id)
|
||||
if hist:
|
||||
prices = [h for h in hist if h["price"] is not None]
|
||||
if prices:
|
||||
low = min(prices, key=lambda h: h["price"])
|
||||
row["lowest_price"] = low["price"]
|
||||
row["lowest_date"] = low["date"]
|
||||
row["max_discount_pct"] = max((h["cut"] or 0) for h in prices)
|
||||
row["times_discounted"] = sum(1 for h in prices if (h["cut"] or 0) > 0)
|
||||
for h in hist:
|
||||
history_rows.append({"app_id": app_id, "name": cur["name"], **h})
|
||||
elif hist is None:
|
||||
low = cheapshark_lowest(app_id)
|
||||
if low:
|
||||
row["lowest_price"] = low["price_usd"]
|
||||
row["lowest_date"] = low["date"] + " (USD)"
|
||||
except requests.RequestException as e:
|
||||
print(f"[{app_id}] History lookup failed: {e}")
|
||||
|
||||
summary_rows.append(row)
|
||||
disc = f"-{cur['discount_pct']}%" if cur["discount_pct"] else "no discount"
|
||||
price = f"{cur['final']:.2f} {cur['currency']}" if cur["final"] is not None else "free/n.a."
|
||||
print(f"[{app_id}] {cur['name']}: {price} ({disc}), lowest ever: {row['lowest_price'] or '?'} {row['lowest_date']}")
|
||||
time.sleep(DELAY)
|
||||
|
||||
if summary_rows:
|
||||
with open("price_summary.csv", "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.DictWriter(f, fieldnames=list(summary_rows[0].keys()))
|
||||
w.writeheader()
|
||||
w.writerows(summary_rows)
|
||||
print("\nWrote price_summary.csv")
|
||||
if history_rows:
|
||||
with open("price_history.csv", "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.DictWriter(f, fieldnames=["app_id", "name", "date", "price", "regular", "cut"])
|
||||
w.writeheader()
|
||||
w.writerows(history_rows)
|
||||
print("Wrote price_history.csv")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user