discordBots/cmd/dealsbot/epic.go
2023-03-06 18:21:40 +01:00

129 lines
3.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"github.com/disgoorg/log"
"io"
"net/http"
"time"
)
type EpicStruct struct {
url string
idPrefix string
deals DealsMap
}
func newEpicApi() EpicStruct {
return EpicStruct{
url: "https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions",
idPrefix: "epic-",
deals: make(map[string]Deal),
}
}
type epicApiBody struct {
Data struct {
Catalog struct {
SearchStore struct {
Elements []struct {
Title string `json:"title"`
Id string `json:"id"`
Description string `json:"description"`
OfferType string `json:"offerType"`
IsCodeRedemptionOnly bool `json:"isCodeRedemptionOnly"`
ProductSlug string `json:"productSlug"`
OfferMappings []struct {
PageSlug string `json:"pageSlug"`
PageType string `json:"pageType"`
} `json:"offerMappings"`
Price struct {
TotalPrice struct {
DiscountPrice int `json:"discountPrice"`
OriginalPrice int `json:"originalPrice"`
Discount int `json:"discount"`
CurrencyCode string `json:"currencyCode"`
} `json:"totalPrice"`
} `json:"price"`
Promotions *struct {
PromotionalOffers []struct {
PromotionalOffers []struct {
StartDate time.Time `json:"startDate"`
EndDate time.Time `json:"endDate"`
DiscountSetting struct {
DiscountType string `json:"discountType"`
DiscountPercentage int `json:"discountPercentage"`
} `json:"discountSetting"`
} `json:"promotionalOffers"`
} `json:"promotionalOffers"`
} `json:"promotions"`
} `json:"elements"`
Paging struct {
Count int `json:"count"`
Total int `json:"total"`
} `json:"paging"`
} `json:"searchStore"`
} `json:"Catalog"`
} `json:"data"`
}
func (e EpicStruct) load() error {
client := &http.Client{}
req, err := http.NewRequest("GET", e.url, nil)
if err != nil {
return err
}
res, err := client.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
var data epicApiBody
err = json.Unmarshal(body, &data)
if err != nil {
return err
}
for _, element := range data.Data.Catalog.SearchStore.Elements {
if element.Promotions == nil ||
len(element.Promotions.PromotionalOffers) == 0 ||
len(element.Promotions.PromotionalOffers[0].PromotionalOffers) == 0 ||
element.Promotions.PromotionalOffers[0].PromotionalOffers[0].DiscountSetting.DiscountPercentage != 0 {
// no deal
continue
}
productSlug := element.ProductSlug
if len(element.OfferMappings) != 0 && productSlug == "" {
productSlug = element.OfferMappings[0].PageSlug
}
if productSlug == "" {
log.Error(fmt.Sprintf("product slug not found for: %v", element.Title))
continue
}
id := fmt.Sprintf("%v%v", e.idPrefix, element.Id)
title := element.Title
url := fmt.Sprintf("https://store.epicgames.com/en-US/p/%v", productSlug)
e.deals[id] = Deal{
Id: id,
Title: title,
Url: url,
}
}
return nil
}
func (e EpicStruct) get() []Deal {
var deals []Deal
for _, deal := range e.deals {
deals = append(deals, deal)
}
return deals
}