client.go 5.9 KB

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