client.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 || o.Discount.DiscountPercentage != 100) {
  140. // DiscountPrice alone is not enough: some offers omit the price
  141. // field (null → 0) while discountPercentage reveals them as
  142. // partial discounts (e.g. Castlevania, Oct 2026).
  143. continue
  144. }
  145. g := game.Game{
  146. Title: el.Title,
  147. ID: "epic-" + el.ID,
  148. Slug: slug,
  149. URL: "https://store.epicgames.com/en-US/p/" + slug,
  150. Store: "epic",
  151. Kind: kind,
  152. Description: el.Description,
  153. Seller: el.Seller.Name,
  154. StartDate: o.StartDate,
  155. EndDate: o.EndDate,
  156. PriceFmt: el.Price.TotalPrice.FmtPrice.OriginalPrice,
  157. }
  158. if o.Discount.DiscountPercentage > 0 && o.Discount.DiscountPercentage < 100 {
  159. g.DiscountPct = o.Discount.DiscountPercentage
  160. // discountPercentage here is the *discount* (e.g. 40 = −40 %),
  161. // not the remaining share. discountPrice (cents) may be absent
  162. // (null → 0) on such offers; then show percent only.
  163. if o.Discount.DiscountPrice > 0 {
  164. g.FinalPriceFmt = fmt.Sprintf("%d.%02d €", o.Discount.DiscountPrice/100, o.Discount.DiscountPrice%100)
  165. }
  166. }
  167. if i := indexOfID(games, g.ID); i >= 0 {
  168. if g.EndDate.After(games[i].EndDate) {
  169. games[i] = g
  170. }
  171. continue
  172. }
  173. games = append(games, g)
  174. }
  175. return games
  176. }
  177. func sortByEnd(games []game.Game) {
  178. sort.Slice(games, func(i, j int) bool {
  179. return games[i].EndDate.Before(games[j].EndDate)
  180. })
  181. }
  182. // GetFreeGames returns the games that are currently free (100 % discount,
  183. // active promotion window), sorted by end date (soonest first).
  184. func (c *Client) GetFreeGames(ctx context.Context) ([]game.Game, error) {
  185. return c.getPromoted(ctx, true)
  186. }
  187. // GetDeals returns currently discounted games (any discount, including free),
  188. // sorted by end date (soonest first).
  189. func (c *Client) GetDeals(ctx context.Context) ([]game.Game, error) {
  190. return c.getPromoted(ctx, false)
  191. }
  192. func (c *Client) getPromoted(ctx context.Context, freeOnly bool) ([]game.Game, error) {
  193. elements, err := c.fetchPromotions(ctx)
  194. if err != nil {
  195. return nil, err
  196. }
  197. now := time.Now()
  198. var games []game.Game
  199. for _, el := range elements {
  200. if el.Promotions == nil {
  201. continue
  202. }
  203. for _, group := range el.Promotions.PromotionalOffers {
  204. games = buildGames(el, "free-now", group.PromotionalOffers,
  205. func(o offer) bool { return !now.Before(o.StartDate) && !now.After(o.EndDate) },
  206. freeOnly, games)
  207. }
  208. }
  209. sortByEnd(games)
  210. return games, nil
  211. }
  212. // GetUpcomingGames returns games whose free period has not started yet
  213. // (announced upcoming giveaways), sorted by start date (soonest first).
  214. func (c *Client) GetUpcomingGames(ctx context.Context) ([]game.Game, error) {
  215. elements, err := c.fetchPromotions(ctx)
  216. if err != nil {
  217. return nil, err
  218. }
  219. now := time.Now()
  220. var games []game.Game
  221. for _, el := range elements {
  222. if el.Promotions == nil {
  223. continue
  224. }
  225. for _, group := range el.Promotions.UpcomingPromotionalOffers {
  226. games = buildGames(el, "upcoming", group.PromotionalOffers,
  227. func(o offer) bool { return o.StartDate.After(now) }, true, games)
  228. }
  229. }
  230. sort.Slice(games, func(i, j int) bool {
  231. return games[i].StartDate.Before(games[j].StartDate)
  232. })
  233. return games, nil
  234. }
  235. // indexOfID returns the index of the game with the given ID, or -1.
  236. func indexOfID(games []game.Game, id string) int {
  237. for i, g := range games {
  238. if g.ID == id {
  239. return i
  240. }
  241. }
  242. return -1
  243. }