client.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. // Name implements game.Provider.
  28. func (c *Client) Name() string { return "epic" }
  29. // Client queries the Epic storefront backend.
  30. type Client struct {
  31. HTTP *http.Client
  32. BaseURL string // override for tests
  33. Country string // ISO 3166 country code, e.g. "DE"
  34. Locale string // e.g. "de", "en-US"
  35. }
  36. // NewClient returns a client with defaults for Germany.
  37. func NewClient() *Client {
  38. return &Client{
  39. HTTP: &http.Client{Timeout: 30 * time.Second},
  40. BaseURL: promotionsURL,
  41. Country: defaultCountry,
  42. Locale: defaultLocale,
  43. }
  44. }
  45. type promotionsResponse struct {
  46. Data struct {
  47. Catalog struct {
  48. SearchStore struct {
  49. Elements []struct {
  50. ID string `json:"id"`
  51. Title string `json:"title"`
  52. Description string `json:"description"`
  53. URLSlug string `json:"urlSlug"`
  54. CatalogNs struct {
  55. Mappings []struct {
  56. PageSlug string `json:"pageSlug"`
  57. } `json:"mappings"`
  58. } `json:"catalogNs"`
  59. Seller struct {
  60. Name string `json:"displayName"`
  61. } `json:"seller"`
  62. Price struct {
  63. TotalPrice struct {
  64. FmtPrice struct {
  65. OriginalPrice string `json:"originalPrice"`
  66. } `json:"fmtPrice"`
  67. } `json:"totalPrice"`
  68. } `json:"price"`
  69. Promotions *struct {
  70. PromotionalOffers []struct {
  71. PromotionalOffers []struct {
  72. StartDate time.Time `json:"startDate"`
  73. EndDate time.Time `json:"endDate"`
  74. Discount struct {
  75. DiscountPrice int `json:"discountPrice"`
  76. } `json:"discountSetting"`
  77. } `json:"promotionalOffers"`
  78. } `json:"promotionalOffers"`
  79. } `json:"promotions"`
  80. } `json:"elements"`
  81. } `json:"searchStore"`
  82. } `json:"Catalog"`
  83. } `json:"data"`
  84. }
  85. // GetFreeGames returns the games that are currently free (100 % discount,
  86. // active promotion window), sorted by end date (soonest first).
  87. func (c *Client) GetFreeGames(ctx context.Context) ([]game.Game, error) {
  88. u, err := url.Parse(c.BaseURL)
  89. if err != nil {
  90. return nil, fmt.Errorf("epic: bad base URL: %w", err)
  91. }
  92. q := u.Query()
  93. q.Set("locale", c.Locale)
  94. q.Set("country", c.Country)
  95. q.Set("allowCountries", c.Country)
  96. u.RawQuery = q.Encode()
  97. req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
  98. if err != nil {
  99. return nil, fmt.Errorf("epic: %w", err)
  100. }
  101. req.Header.Set("User-Agent", userAgent)
  102. req.Header.Set("Accept", "application/json")
  103. resp, err := c.HTTP.Do(req)
  104. if err != nil {
  105. return nil, fmt.Errorf("epic: request failed: %w", err)
  106. }
  107. defer resp.Body.Close()
  108. if resp.StatusCode != http.StatusOK {
  109. return nil, fmt.Errorf("epic: unexpected status %s", resp.Status)
  110. }
  111. var pr promotionsResponse
  112. if err := json.NewDecoder(resp.Body).Decode(&pr); err != nil {
  113. return nil, fmt.Errorf("epic: decode response: %w", err)
  114. }
  115. now := time.Now()
  116. var games []game.Game
  117. for _, el := range pr.Data.Catalog.SearchStore.Elements {
  118. if el.Promotions == nil {
  119. continue
  120. }
  121. for _, offerGroup := range el.Promotions.PromotionalOffers {
  122. for _, offer := range offerGroup.PromotionalOffers {
  123. // Free = 100 % discount, and the window must be active right now.
  124. if offer.Discount.DiscountPrice != 0 {
  125. continue
  126. }
  127. if now.Before(offer.StartDate) || now.After(offer.EndDate) {
  128. continue
  129. }
  130. slug := el.URLSlug
  131. if len(el.CatalogNs.Mappings) > 0 && el.CatalogNs.Mappings[0].PageSlug != "" {
  132. // urlSlug is sometimes a wrong ID (see vogler/free-games-claimer,
  133. // epic-games.js comment on spirit-of-the-north): prefer the
  134. // catalog mapping's page slug.
  135. slug = el.CatalogNs.Mappings[0].PageSlug
  136. }
  137. g := game.Game{
  138. Title: el.Title,
  139. ID: "epic-" + el.ID,
  140. Slug: slug,
  141. URL: "https://store.epicgames.com/en-US/p/" + slug,
  142. Store: "epic",
  143. Kind: "free-now",
  144. Description: el.Description,
  145. Seller: el.Seller.Name,
  146. StartDate: offer.StartDate,
  147. EndDate: offer.EndDate,
  148. PriceFmt: el.Price.TotalPrice.FmtPrice.OriginalPrice,
  149. }
  150. // A game can appear with several promotion windows (e.g. extended
  151. // giveaway); keep the one with the latest end date.
  152. if i := indexOfID(games, g.ID); i >= 0 {
  153. if g.EndDate.After(games[i].EndDate) {
  154. games[i] = g
  155. }
  156. continue
  157. }
  158. games = append(games, g)
  159. }
  160. }
  161. }
  162. sort.Slice(games, func(i, j int) bool {
  163. return games[i].EndDate.Before(games[j].EndDate)
  164. })
  165. return games, nil
  166. }
  167. // indexOfID returns the index of the game with the given ID, or -1.
  168. func indexOfID(games []game.Game, id string) int {
  169. for i, g := range games {
  170. if g.ID == id {
  171. return i
  172. }
  173. }
  174. return -1
  175. }