client.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 is el.price.totalPrice.discountPrice == 0
  141. // (the element's current price). The offer's discountSetting fields
  142. // are unreliable: discountPrice is null (=0 in Go) even for
  143. // non-free offers, and discountPercentage carries inconsistent
  144. // values (e.g. Castlevania 40 while the store shows −60 %).
  145. // - freeOnly: element current price must be 0.
  146. // - deals: current price > 0; discount display from
  147. // fmtPrice (original → current).
  148. currentlyFree := el.Price.TotalPrice.DiscountPrice == 0
  149. if freeOnly != currentlyFree {
  150. continue
  151. }
  152. g := game.Game{
  153. Title: el.Title,
  154. ID: "epic-" + el.ID,
  155. Slug: slug,
  156. URL: "https://store.epicgames.com/en-US/p/" + slug,
  157. Store: "epic",
  158. Kind: kind,
  159. Description: el.Description,
  160. Seller: el.Seller.Name,
  161. StartDate: o.StartDate,
  162. EndDate: o.EndDate,
  163. PriceFmt: el.Price.TotalPrice.FmtPrice.OriginalPrice,
  164. }
  165. if !currentlyFree {
  166. g.Kind = "deal"
  167. g.FinalPriceFmt = el.Price.TotalPrice.FmtPrice.DiscountPrice
  168. if orig := el.Price.TotalPrice.FmtPrice.OriginalPrice; orig != "" {
  169. g.PriceFmt = orig
  170. }
  171. // Compute the discount percent from the prices (cents).
  172. if cur := el.Price.TotalPrice.DiscountPrice; cur > 0 && cur < el.Price.TotalPrice.OriginalPrice {
  173. orig := el.Price.TotalPrice.OriginalPrice
  174. g.DiscountPct = (orig - cur) * 100 / orig
  175. }
  176. }
  177. if i := indexOfID(games, g.ID); i >= 0 {
  178. if g.EndDate.After(games[i].EndDate) {
  179. games[i] = g
  180. }
  181. continue
  182. }
  183. games = append(games, g)
  184. }
  185. return games
  186. }
  187. func sortByEnd(games []game.Game) {
  188. sort.Slice(games, func(i, j int) bool {
  189. return games[i].EndDate.Before(games[j].EndDate)
  190. })
  191. }
  192. // GetFreeGames returns the games that are currently free (100 % discount,
  193. // active promotion window), sorted by end date (soonest first).
  194. func (c *Client) GetFreeGames(ctx context.Context) ([]game.Game, error) {
  195. return c.getPromoted(ctx, true)
  196. }
  197. // GetDeals returns currently discounted games (any discount, including free),
  198. // sorted by end date (soonest first).
  199. func (c *Client) GetDeals(ctx context.Context) ([]game.Game, error) {
  200. return c.getPromoted(ctx, false)
  201. }
  202. func (c *Client) getPromoted(ctx context.Context, freeOnly bool) ([]game.Game, error) {
  203. elements, err := c.fetchPromotions(ctx)
  204. if err != nil {
  205. return nil, err
  206. }
  207. now := time.Now()
  208. var games []game.Game
  209. for _, el := range elements {
  210. if el.Promotions == nil {
  211. continue
  212. }
  213. for _, group := range el.Promotions.PromotionalOffers {
  214. games = buildGames(el, "free-now", group.PromotionalOffers,
  215. func(o offer) bool { return !now.Before(o.StartDate) && !now.After(o.EndDate) },
  216. freeOnly, games)
  217. }
  218. }
  219. sortByEnd(games)
  220. return games, nil
  221. }
  222. // GetUpcomingGames returns games whose free period has not started yet
  223. // (announced upcoming giveaways), sorted by start date (soonest first).
  224. func (c *Client) GetUpcomingGames(ctx context.Context) ([]game.Game, error) {
  225. elements, err := c.fetchPromotions(ctx)
  226. if err != nil {
  227. return nil, err
  228. }
  229. now := time.Now()
  230. var games []game.Game
  231. for _, el := range elements {
  232. if el.Promotions == nil {
  233. continue
  234. }
  235. for _, group := range el.Promotions.UpcomingPromotionalOffers {
  236. games = buildGames(el, "upcoming", group.PromotionalOffers,
  237. func(o offer) bool { return o.StartDate.After(now) }, true, games)
  238. }
  239. }
  240. sort.Slice(games, func(i, j int) bool {
  241. return games[i].StartDate.Before(games[j].StartDate)
  242. })
  243. return games, nil
  244. }
  245. // indexOfID returns the index of the game with the given ID, or -1.
  246. func indexOfID(games []game.Game, id string) int {
  247. for i, g := range games {
  248. if g.ID == id {
  249. return i
  250. }
  251. }
  252. return -1
  253. }