client.go 7.5 KB

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