client.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. } `json:"discountSetting"`
  51. }
  52. type element struct {
  53. ID string `json:"id"`
  54. Title string `json:"title"`
  55. Description string `json:"description"`
  56. URLSlug string `json:"urlSlug"`
  57. CatalogNs struct {
  58. Mappings []struct {
  59. PageSlug string `json:"pageSlug"`
  60. } `json:"mappings"`
  61. } `json:"catalogNs"`
  62. Seller struct {
  63. Name string `json:"displayName"`
  64. } `json:"seller"`
  65. Price struct {
  66. TotalPrice struct {
  67. FmtPrice struct {
  68. OriginalPrice string `json:"originalPrice"`
  69. } `json:"fmtPrice"`
  70. } `json:"totalPrice"`
  71. } `json:"price"`
  72. Promotions *struct {
  73. PromotionalOffers []struct {
  74. PromotionalOffers []offer `json:"promotionalOffers"`
  75. } `json:"promotionalOffers"`
  76. UpcomingPromotionalOffers []struct {
  77. PromotionalOffers []offer `json:"promotionalOffers"`
  78. } `json:"upcomingPromotionalOffers"`
  79. } `json:"promotions"`
  80. }
  81. type promotionsResponse struct {
  82. Data struct {
  83. Catalog struct {
  84. SearchStore struct {
  85. Elements []element `json:"elements"`
  86. } `json:"searchStore"`
  87. } `json:"Catalog"`
  88. } `json:"data"`
  89. }
  90. // fetchPromotions retrieves and decodes the promotions document.
  91. func (c *Client) fetchPromotions(ctx context.Context) ([]element, error) {
  92. u, err := url.Parse(c.BaseURL)
  93. if err != nil {
  94. return nil, fmt.Errorf("epic: bad base URL: %w", err)
  95. }
  96. q := u.Query()
  97. q.Set("locale", c.Locale)
  98. q.Set("country", c.Country)
  99. q.Set("allowCountries", c.Country)
  100. u.RawQuery = q.Encode()
  101. req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
  102. if err != nil {
  103. return nil, fmt.Errorf("epic: %w", err)
  104. }
  105. req.Header.Set("User-Agent", userAgent)
  106. req.Header.Set("Accept", "application/json")
  107. resp, err := c.HTTP.Do(req)
  108. if err != nil {
  109. return nil, fmt.Errorf("epic: request failed: %w", err)
  110. }
  111. defer resp.Body.Close()
  112. if resp.StatusCode != http.StatusOK {
  113. return nil, fmt.Errorf("epic: unexpected status %s", resp.Status)
  114. }
  115. var pr promotionsResponse
  116. if err := json.NewDecoder(resp.Body).Decode(&pr); err != nil {
  117. return nil, fmt.Errorf("epic: decode response: %w", err)
  118. }
  119. return pr.Data.Catalog.SearchStore.Elements, nil
  120. }
  121. // buildGames converts the offer windows of one element into games. Windows
  122. // that do not satisfy keep are skipped; a game appearing with several windows
  123. // (e.g. extended giveaway) keeps the one with the latest end date.
  124. func buildGames(el element, kind string, windows []offer, keep func(offer) bool, games []game.Game) []game.Game {
  125. slug := el.URLSlug
  126. if len(el.CatalogNs.Mappings) > 0 && el.CatalogNs.Mappings[0].PageSlug != "" {
  127. // urlSlug is sometimes a wrong ID (see vogler/free-games-claimer,
  128. // epic-games.js comment on spirit-of-the-north): prefer the catalog
  129. // mapping's page slug.
  130. slug = el.CatalogNs.Mappings[0].PageSlug
  131. }
  132. for _, o := range windows {
  133. if o.Discount.DiscountPrice != 0 || !keep(o) {
  134. continue
  135. }
  136. g := game.Game{
  137. Title: el.Title,
  138. ID: "epic-" + el.ID,
  139. Slug: slug,
  140. URL: "https://store.epicgames.com/en-US/p/" + slug,
  141. Store: "epic",
  142. Kind: kind,
  143. Description: el.Description,
  144. Seller: el.Seller.Name,
  145. StartDate: o.StartDate,
  146. EndDate: o.EndDate,
  147. PriceFmt: el.Price.TotalPrice.FmtPrice.OriginalPrice,
  148. }
  149. if i := indexOfID(games, g.ID); i >= 0 {
  150. if g.EndDate.After(games[i].EndDate) {
  151. games[i] = g
  152. }
  153. continue
  154. }
  155. games = append(games, g)
  156. }
  157. return games
  158. }
  159. func sortByEnd(games []game.Game) {
  160. sort.Slice(games, func(i, j int) bool {
  161. return games[i].EndDate.Before(games[j].EndDate)
  162. })
  163. }
  164. // GetFreeGames returns the games that are currently free (100 % discount,
  165. // active promotion window), sorted by end date (soonest first).
  166. func (c *Client) GetFreeGames(ctx context.Context) ([]game.Game, error) {
  167. elements, err := c.fetchPromotions(ctx)
  168. if err != nil {
  169. return nil, err
  170. }
  171. now := time.Now()
  172. var games []game.Game
  173. for _, el := range elements {
  174. if el.Promotions == nil {
  175. continue
  176. }
  177. for _, group := range el.Promotions.PromotionalOffers {
  178. games = buildGames(el, "free-now", group.PromotionalOffers,
  179. func(o offer) bool { return !now.Before(o.StartDate) && !now.After(o.EndDate) }, games)
  180. }
  181. }
  182. sortByEnd(games)
  183. return games, nil
  184. }
  185. // GetUpcomingGames returns games whose free period has not started yet
  186. // (announced upcoming giveaways), sorted by start date (soonest first).
  187. func (c *Client) GetUpcomingGames(ctx context.Context) ([]game.Game, error) {
  188. elements, err := c.fetchPromotions(ctx)
  189. if err != nil {
  190. return nil, err
  191. }
  192. now := time.Now()
  193. var games []game.Game
  194. for _, el := range elements {
  195. if el.Promotions == nil {
  196. continue
  197. }
  198. for _, group := range el.Promotions.UpcomingPromotionalOffers {
  199. games = buildGames(el, "upcoming", group.PromotionalOffers,
  200. func(o offer) bool { return o.StartDate.After(now) }, games)
  201. }
  202. }
  203. sort.Slice(games, func(i, j int) bool {
  204. return games[i].StartDate.Before(games[j].StartDate)
  205. })
  206. return games, nil
  207. }
  208. // indexOfID returns the index of the game with the given ID, or -1.
  209. func indexOfID(games []game.Game, id string) int {
  210. for i, g := range games {
  211. if g.ID == id {
  212. return i
  213. }
  214. }
  215. return -1
  216. }