client.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Package epic implements a client for the Epic Games Store's public
  2. // storefront backend to discover free games.
  3. //
  4. // Reference: vogler/free-games-claimer (epic-games.js) scrapes the rendered
  5. // "Free Games" page; it also notes (epic-games.js, line ~151) that the page is
  6. // built from the JSON served by the storefront backend. We query that JSON
  7. // directly, so no browser is needed.
  8. package epic
  9. import (
  10. "context"
  11. "encoding/json"
  12. "fmt"
  13. "net/http"
  14. "net/url"
  15. "sort"
  16. "time"
  17. "gogs.netdome.biz/paul/cheapo/internal/game"
  18. )
  19. const (
  20. // promotionsURL is the public backend endpoint that powers the
  21. // "Free Games" page of the Epic Games Store.
  22. promotionsURL = "https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions"
  23. defaultCountry = "DE"
  24. defaultLocale = "de"
  25. userAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0"
  26. )
  27. // Client queries the Epic storefront backend.
  28. type Client struct {
  29. HTTP *http.Client
  30. BaseURL string // override for tests
  31. Country string // ISO 3166 country code, e.g. "DE"
  32. Locale string // e.g. "de", "en-US"
  33. }
  34. // NewClient returns a client with defaults for Germany.
  35. func NewClient() *Client {
  36. return &Client{
  37. HTTP: &http.Client{Timeout: 30 * time.Second},
  38. BaseURL: promotionsURL,
  39. Country: defaultCountry,
  40. Locale: defaultLocale,
  41. }
  42. }
  43. // Name implements game.Provider.
  44. func (c *Client) Name() string { return "epic" }
  45. type offer struct {
  46. StartDate time.Time `json:"startDate"`
  47. EndDate time.Time `json:"endDate"`
  48. Discount struct {
  49. DiscountPrice int `json:"discountPrice"`
  50. DiscountPercentage int `json:"discountPercentage"`
  51. } `json:"discountSetting"`
  52. }
  53. type element struct {
  54. ID string `json:"id"`
  55. Title string `json:"title"`
  56. Description string `json:"description"`
  57. URLSlug string `json:"urlSlug"`
  58. CatalogNs struct {
  59. Mappings []struct {
  60. PageSlug string `json:"pageSlug"`
  61. } `json:"mappings"`
  62. } `json:"catalogNs"`
  63. Seller struct {
  64. Name string `json:"displayName"`
  65. } `json:"seller"`
  66. Price *struct {
  67. TotalPrice struct {
  68. DiscountPrice int `json:"discountPrice"` // current price in cents; 0 = free
  69. OriginalPrice int `json:"originalPrice"` // list price in cents
  70. FmtPrice struct {
  71. OriginalPrice string `json:"originalPrice"`
  72. DiscountPrice string `json:"discountPrice"` // formatted current price
  73. } `json:"fmtPrice"`
  74. } `json:"totalPrice"`
  75. } `json:"price"`
  76. Promotions *struct {
  77. PromotionalOffers []struct {
  78. PromotionalOffers []offer `json:"promotionalOffers"`
  79. } `json:"promotionalOffers"`
  80. UpcomingPromotionalOffers []struct {
  81. PromotionalOffers []offer `json:"promotionalOffers"`
  82. } `json:"upcomingPromotionalOffers"`
  83. } `json:"promotions"`
  84. }
  85. type promotionsResponse struct {
  86. Data struct {
  87. Catalog struct {
  88. SearchStore struct {
  89. Elements []element `json:"elements"`
  90. } `json:"searchStore"`
  91. } `json:"Catalog"`
  92. } `json:"data"`
  93. }
  94. // fetchPromotions retrieves and decodes the promotions document.
  95. func (c *Client) fetchPromotions(ctx context.Context) ([]element, error) {
  96. u, err := url.Parse(c.BaseURL)
  97. if err != nil {
  98. return nil, fmt.Errorf("epic: bad base URL: %w", err)
  99. }
  100. q := u.Query()
  101. q.Set("locale", c.Locale)
  102. q.Set("country", c.Country)
  103. q.Set("allowCountries", c.Country)
  104. u.RawQuery = q.Encode()
  105. req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
  106. if err != nil {
  107. return nil, fmt.Errorf("epic: %w", err)
  108. }
  109. req.Header.Set("User-Agent", userAgent)
  110. req.Header.Set("Accept", "application/json")
  111. resp, err := c.HTTP.Do(req)
  112. if err != nil {
  113. return nil, fmt.Errorf("epic: request failed: %w", err)
  114. }
  115. defer resp.Body.Close()
  116. if resp.StatusCode != http.StatusOK {
  117. return nil, fmt.Errorf("epic: unexpected status %s", resp.Status)
  118. }
  119. var pr promotionsResponse
  120. if err := json.NewDecoder(resp.Body).Decode(&pr); err != nil {
  121. return nil, fmt.Errorf("epic: decode response: %w", err)
  122. }
  123. return pr.Data.Catalog.SearchStore.Elements, nil
  124. }
  125. // buildGames converts the offer windows of one element into games. Windows
  126. // that do not satisfy keep are skipped; a game appearing with several windows
  127. // (e.g. extended giveaway) keeps the one with the latest end date. When
  128. // freeOnly is true, only 100 % discounts pass; otherwise discounted deals are
  129. // included too.
  130. func buildGames(el element, kind string, windows []offer, keep func(offer) bool, freeOnly bool, games []game.Game) []game.Game {
  131. slug := el.URLSlug
  132. if len(el.CatalogNs.Mappings) > 0 && el.CatalogNs.Mappings[0].PageSlug != "" {
  133. // urlSlug is sometimes a wrong ID (see vogler/free-games-claimer,
  134. // epic-games.js comment on spirit-of-the-north): prefer the catalog
  135. // mapping's page slug.
  136. slug = el.CatalogNs.Mappings[0].PageSlug
  137. }
  138. for _, o := range windows {
  139. // Semantics verified against the live API (Oct 2026): the ONLY
  140. // reliable free indicator for CURRENT windows is
  141. // el.price.totalPrice.discountPrice == 0 (the element's current
  142. // price). The offer's discountSetting fields are unreliable:
  143. // discountPrice is null (=0 in Go) even for non-free offers, and
  144. // discountPercentage carries inconsistent values (e.g. Castlevania
  145. // 40 while the store shows −60 %).
  146. //
  147. // UPCOMING windows announce a future giveaway — the element's
  148. // current price says nothing about that window, so they are always
  149. // included as "upcoming".
  150. if el.Price == nil {
  151. // No price information at all → cannot classify; skip. Missing
  152. // price data must not read as "free" (same quirk class as the
  153. // null discountPrice).
  154. continue
  155. }
  156. currentlyFree := el.Price.TotalPrice.DiscountPrice == 0
  157. isUpcoming := kind == "upcoming"
  158. if !isUpcoming && freeOnly != currentlyFree {
  159. continue
  160. }
  161. g := game.Game{
  162. Title: el.Title,
  163. ID: "epic-" + el.ID,
  164. Slug: slug,
  165. URL: "https://store.epicgames.com/en-US/p/" + slug,
  166. Store: "epic",
  167. Kind: kind,
  168. Description: el.Description,
  169. Seller: el.Seller.Name,
  170. StartDate: o.StartDate,
  171. EndDate: o.EndDate,
  172. PriceFmt: el.Price.TotalPrice.FmtPrice.OriginalPrice,
  173. }
  174. if !isUpcoming && !currentlyFree {
  175. g.Kind = "deal"
  176. g.FinalPriceFmt = el.Price.TotalPrice.FmtPrice.DiscountPrice
  177. if orig := el.Price.TotalPrice.FmtPrice.OriginalPrice; orig != "" {
  178. g.PriceFmt = orig
  179. }
  180. // Compute the discount percent from the prices (cents).
  181. if cur := el.Price.TotalPrice.DiscountPrice; cur > 0 && cur < el.Price.TotalPrice.OriginalPrice {
  182. orig := el.Price.TotalPrice.OriginalPrice
  183. g.DiscountPct = (orig - cur) * 100 / orig
  184. }
  185. }
  186. if i := indexOfID(games, g.ID); i >= 0 {
  187. if g.EndDate.After(games[i].EndDate) {
  188. games[i] = g
  189. }
  190. continue
  191. }
  192. games = append(games, g)
  193. }
  194. return games
  195. }
  196. func sortByEnd(games []game.Game) {
  197. sort.Slice(games, func(i, j int) bool {
  198. return games[i].EndDate.Before(games[j].EndDate)
  199. })
  200. }
  201. // GetFreeGames returns the games that are currently free (100 % discount,
  202. // active promotion window), sorted by end date (soonest first).
  203. func (c *Client) GetFreeGames(ctx context.Context) ([]game.Game, error) {
  204. return c.getPromoted(ctx, true)
  205. }
  206. // GetDeals returns currently discounted games (any discount, including free),
  207. // sorted by end date (soonest first).
  208. func (c *Client) GetDeals(ctx context.Context) ([]game.Game, error) {
  209. return c.getPromoted(ctx, false)
  210. }
  211. func (c *Client) getPromoted(ctx context.Context, freeOnly bool) ([]game.Game, error) {
  212. elements, err := c.fetchPromotions(ctx)
  213. if err != nil {
  214. return nil, err
  215. }
  216. now := time.Now()
  217. var games []game.Game
  218. for _, el := range elements {
  219. if el.Promotions == nil {
  220. continue
  221. }
  222. for _, group := range el.Promotions.PromotionalOffers {
  223. games = buildGames(el, "free-now", group.PromotionalOffers,
  224. func(o offer) bool { return !now.Before(o.StartDate) && !now.After(o.EndDate) },
  225. freeOnly, games)
  226. }
  227. }
  228. sortByEnd(games)
  229. return games, nil
  230. }
  231. // GetUpcomingGames returns games whose free period has not started yet
  232. // (announced upcoming giveaways), sorted by start date (soonest first).
  233. func (c *Client) GetUpcomingGames(ctx context.Context) ([]game.Game, error) {
  234. elements, err := c.fetchPromotions(ctx)
  235. if err != nil {
  236. return nil, err
  237. }
  238. now := time.Now()
  239. var games []game.Game
  240. for _, el := range elements {
  241. if el.Promotions == nil {
  242. continue
  243. }
  244. for _, group := range el.Promotions.UpcomingPromotionalOffers {
  245. games = buildGames(el, "upcoming", group.PromotionalOffers,
  246. func(o offer) bool { return o.StartDate.After(now) }, true, games)
  247. }
  248. }
  249. sort.Slice(games, func(i, j int) bool {
  250. return games[i].StartDate.Before(games[j].StartDate)
  251. })
  252. return games, nil
  253. }
  254. // indexOfID returns the index of the game with the given ID, or -1.
  255. func indexOfID(games []game.Game, id string) int {
  256. for i, g := range games {
  257. if g.ID == id {
  258. return i
  259. }
  260. }
  261. return -1
  262. }