Compare commits

..

No commits in common. "master" and "v0.1.7" have entirely different histories.

12 changed files with 94 additions and 260 deletions

4
api.go
View File

@ -97,10 +97,6 @@ func (s *Sorare) Debug() *Sorare {
return s return s
} }
func (s *Sorare) SetApiKey(apiKey string) {
s.Client.SetApiKey(apiKey)
}
func (s *Sorare) SetJWTToken(token graphql.JwtToken, audience string) { func (s *Sorare) SetJWTToken(token graphql.JwtToken, audience string) {
s.Client.SetJWTToken(token, audience) s.Client.SetJWTToken(token, audience)
} }

View File

@ -31,48 +31,39 @@ func main() {
ctx := context.Background() ctx := context.Background()
p, err := api.Football.Player.Get(ctx, graphql.SlugParams{Slug: "joshua-kimmich"}) si, err := api.ShopItems.Get(ctx, sorare.ShopItemsParams{
Types: []sorare.ShopItemType{sorare.ShopItemTypeLevelUp},
UnlockedOnly: true,
})
if err != nil { if err != nil {
panic(err) panic(err)
} }
log.Printf("%+v", p) for _, item := range si {
log.Printf(
"%s %d %d %s %s",
item.TypeName,
item.ShopItemInterface.MyBalance,
item.ShopItemInterface.Price,
item.LevelUpShopItem.Rarity,
time.Until(item.ShopItemInterface.MyLimitResetAt).String(),
)
}
// si, err := api.ShopItems.Get(ctx, sorare.ShopItemsParams{ cu, err := api.Users.CurrentUser.Get(ctx, graphql.EmptyParams{})
// Types: []sorare.ShopItemType{sorare.ShopItemTypeLevelUp}, if err != nil {
// UnlockedOnly: true, panic(err)
// }) }
// if err != nil { log.Printf("%d", cu.CoinBalance)
// panic(err) // cu, err := api.Users.FootballCards("gigiz22").Get(ctx, football.CardsParams{
// }
// for _, item := range si {
// log.Printf(
// "%s %d %d %s %s",
// item.TypeName,
// item.ShopItemInterface.MyBalance,
// item.ShopItemInterface.Price,
// item.LevelUpShopItem.Rarity,
// time.Until(item.ShopItemInterface.MyLimitResetAt).String(),
// )
// }
// cu, err := api.Users.CurrentUser.Get(ctx, graphql.EmptyParams{})
// if err != nil {
// panic(err)
// }
// log.Printf("%d", cu.CoinBalance)
// cards, err := api.Users.FootballCards("gigiz22").Get(ctx, football.CardsParams{
// Rarities: []types.Rarity{types.RarityLimited}, // Rarities: []types.Rarity{types.RarityLimited},
// }) // })
// if err != nil { // if err != nil {
// panic(err) // panic(err)
// } // }
// sort.Slice(cards, func(i, j int) bool { // sort.Slice(cu, func(i, j int) bool {
// return cards[i].XpNeededForNextGrade-cards[i].Xp > cards[j].XpNeededForNextGrade-cards[j].Xp // return cu[i].XpNeededForNextGrade-cu[i].Xp > cu[j].XpNeededForNextGrade-cu[j].Xp
// }) // })
// for _, card := range cards { // for _, card := range cu {
// if !card.InSeasonEligible {
// continue
// }
// log.Printf( // log.Printf(
// "%60s %2d %6d %6d %6d (%d/%d)", // "%60s %2d %6d %6d %6d (%d/%d)",
// card.Token.Name, // card.Token.Name,

View File

@ -26,8 +26,7 @@ type Football struct {
Players *graphql.Query[[]Player, graphql.SlugsParams] Players *graphql.Query[[]Player, graphql.SlugsParams]
Season *graphql.Query[Season, SeasonParams] Season *graphql.Query[Season, SeasonParams]
So5 *So5 So5 *So5
Rivals *Rivals
} }
func NewFootball(c *graphql.Client) *Football { func NewFootball(c *graphql.Client) *Football {
@ -110,14 +109,13 @@ func NewFootball(c *graphql.Client) *Football {
c, c,
"players", "players",
[]string{"football"}, []string{"football"},
).WithMaxPageSize(100), ),
Season: graphql.NewQuery[Season, SeasonParams]( Season: graphql.NewQuery[Season, SeasonParams](
c, c,
"season", "season",
[]string{"football"}, []string{"football"},
), ),
So5: NewSo5(c), So5: NewSo5(c),
Rivals: NewRivals(c),
} }
} }

View File

@ -40,20 +40,6 @@ type CardSupply struct {
Unique int `graphql:"unique"` Unique int `graphql:"unique"`
} }
type MembershipStats struct {
Season struct {
StartYear int `graphql:"startYear"`
} `graphql:"season"`
Appearances int `graphql:"appearances"`
Goals int `graphql:"goals"`
Assists int `graphql:"assists"`
YellowCards int `graphql:"yellowCards"`
RedCards int `graphql:"redCards"`
MinutesPlayed int `graphql:"minutesPlayed"`
SubstituteIn int `graphql:"substituteIn"`
SubstituteOut int `graphql:"substituteOut"`
}
type Membership struct { type Membership struct {
Id graphql.Id `graphql:"id"` Id graphql.Id `graphql:"id"`
StartDate time.Time `graphql:"startDate"` StartDate time.Time `graphql:"startDate"`
@ -67,7 +53,6 @@ type Membership struct {
Slug string `graphql:"slug"` Slug string `graphql:"slug"`
} `graphql:"... on NationalTeam"` } `graphql:"... on NationalTeam"`
} `graphql:"membershipTeam"` } `graphql:"membershipTeam"`
//Stats []MembershipStats `graphql:"stats"`
} }
type Player struct { type Player struct {

View File

@ -1,17 +0,0 @@
package football
import "git.lehouerou.net/laurent/sorare/graphql"
type Rivals struct {
c *graphql.Client
PastGames *graphql.PaginatedQuery[RivalsGame, graphql.EmptyParams]
}
func NewRivals(c *graphql.Client) *Rivals {
return &Rivals{
c: c,
PastGames: graphql.NewPaginatedQuery[RivalsGame, graphql.EmptyParams](c, "pastGamesPaginated", []string{"football", "rivals"}).WithOverrideComplexity(107),
}
}

View File

@ -1,32 +0,0 @@
package football
import (
"git.lehouerou.net/laurent/sorare/graphql"
"git.lehouerou.net/laurent/sorare/types"
)
type RivalsDraftableObject struct {
Id graphql.Id `graphql:"id"`
CapValue float64 `graphql:"capValue"`
Player struct {
Slug string `graphql:"slug"`
ActiveClub struct {
Slug string `graphql:"slug"`
}
ActiveNationalTeam struct {
Slug string `graphql:"slug"`
}
} `graphql:"player"`
Position types.Position `graphql:"position"`
}
type RivalsGame struct {
Id graphql.Id `graphql:"id"`
Slug string `graphql:"slug"`
Cap int `graphql:"cap"`
DraftablePlayers []RivalsDraftableObject `graphql:"draftablePlayers"`
FormationKnown bool `graphql:"formationKnown"`
Game struct {
Id graphql.Id `graphql:"id"`
} `graphql:"game"`
}

View File

@ -22,28 +22,28 @@ func NewSo5(c *graphql.Client) *So5 {
So5Fixture: graphql.NewQuery[So5Fixture, So5FixtureParams]( So5Fixture: graphql.NewQuery[So5Fixture, So5FixtureParams](
c, c,
"so5Fixture", "so5Fixture",
[]string{"so5"}, []string{"football", "so5"},
), ),
So5Fixtures: graphql.NewPaginatedQuery[So5Fixture, So5FixturesParams]( So5Fixtures: graphql.NewPaginatedQuery[So5Fixture, So5FixturesParams](
c, c,
"so5Fixtures", "so5Fixtures",
[]string{"so5"}, []string{"football", "so5"},
), ),
So5Score: graphql.NewQuery[So5Score, graphql.IdParams]( So5Score: graphql.NewQuery[So5Score, graphql.IdParams](
c, c,
"so5Score", "so5Score",
[]string{"so5"}, []string{"football", "so5"},
), ),
So5Leaderboard: graphql.NewQuery[So5Leaderboard, graphql.SlugParams]( So5Leaderboard: graphql.NewQuery[So5Leaderboard, graphql.SlugParams](
c, c,
"so5Leaderboard", "so5Leaderboard",
[]string{"so5"}, []string{"football", "so5"},
), ),
UpcomingLeaderboards: graphql.NewQuery[[]So5Leaderboard, UpcomingLeaderboardsParams]( UpcomingLeaderboards: graphql.NewQuery[[]So5Leaderboard, UpcomingLeaderboardsParams](
c, c,
"upcomingLeaderboards", "upcomingLeaderboards",
[]string{"so5"}, []string{"football", "so5"},
), ),
} }
} }

View File

@ -57,10 +57,10 @@ type JwtToken struct {
type SignIn struct { type SignIn struct {
CurrentUser struct { CurrentUser struct {
Slug string Slug string
JwtToken JwtToken `graphql:"jwtToken(aud: $aud)"`
} `graphql:"currentUser"` } `graphql:"currentUser"`
OtpSessionChallenge string OtpSessionChallenge string
JwtToken JwtToken `graphql:"jwtToken(aud: $aud)"`
Errors []struct { Errors []struct {
Message string Message string
} `graphql:"errors"` } `graphql:"errors"`
@ -116,12 +116,12 @@ func (c *Client) getNewToken(
} }
if len(res.Errors) == 0 { if len(res.Errors) == 0 {
if res.JwtToken.Token == "" { if res.CurrentUser.JwtToken.Token == "" {
return JwtToken{}, errors.New( return JwtToken{}, errors.New(
"no errors & no jwt token returned on email/password mutation", "no errors & no jwt token returned on email/password mutation",
) )
} }
return res.JwtToken, nil return res.CurrentUser.JwtToken, nil
} }
if res.Errors[0].Message == "invalid" { if res.Errors[0].Message == "invalid" {
@ -146,10 +146,10 @@ func (c *Client) getNewToken(
} }
if len(resOtp.Errors) == 0 { if len(resOtp.Errors) == 0 {
if resOtp.JwtToken.Token == "" { if resOtp.CurrentUser.JwtToken.Token == "" {
return JwtToken{}, errors.New("no errors & no jwt token returned on otp mutation") return JwtToken{}, errors.New("no errors & no jwt token returned on otp mutation")
} }
return resOtp.JwtToken, nil return resOtp.CurrentUser.JwtToken, nil
} }
return JwtToken{}, errors.Errorf("validating otp: %s", resOtp.Errors[0].Message) return JwtToken{}, errors.Errorf("validating otp: %s", resOtp.Errors[0].Message)
} }

View File

@ -3,7 +3,6 @@ package graphql
import ( import (
"context" "context"
"net/http" "net/http"
"reflect"
"sync" "sync"
"time" "time"
@ -23,11 +22,9 @@ type Client struct {
httpClient *http.Client httpClient *http.Client
gql *graphql.Client gql *graphql.Client
rl *rate.Limiter rl *rate.Limiter
apirl *rate.Limiter
lock *sync.Mutex lock *sync.Mutex
authenticated bool authenticated bool
token JwtToken token JwtToken
apiKey string
} }
func NewClient(httpclient *http.Client, baseUrl string) *Client { func NewClient(httpclient *http.Client, baseUrl string) *Client {
@ -35,7 +32,6 @@ func NewClient(httpclient *http.Client, baseUrl string) *Client {
httpClient: httpclient, httpClient: httpclient,
gql: graphql.NewClient(baseUrl, httpclient), gql: graphql.NewClient(baseUrl, httpclient),
rl: rate.NewLimiter(rate.Every(rateLimitPeriod), rateLimitBurst), rl: rate.NewLimiter(rate.Every(rateLimitPeriod), rateLimitBurst),
apirl: rate.NewLimiter(rate.Every(rateLimitPeriod/10), rateLimitBurst*10),
lock: &sync.Mutex{}, lock: &sync.Mutex{},
authenticated: false, authenticated: false,
} }
@ -54,18 +50,12 @@ func (c *Client) SetJWTToken(token JwtToken, audience string) {
c.authenticated = true c.authenticated = true
} }
func (c *Client) SetApiKey(apiKey string) { func (c *Client) MaxComplexity() int {
c.gql = c.gql.WithRequestModifier(func(request *http.Request) { if c.authenticated {
request.Header.Set("APIKEY", apiKey)
})
c.apiKey = apiKey
}
func (c *Client) MaxQueryComplexity() int {
if c.apiKey != "" || c.authenticated {
return MaxAuthenticatedQueryComplexity return MaxAuthenticatedQueryComplexity
} else {
return MaxAnonymousQueryComplexity
} }
return MaxAnonymousQueryComplexity
} }
func (c *Client) ConstructRawQuery( func (c *Client) ConstructRawQuery(
@ -81,16 +71,9 @@ func (c *Client) Query(
variables interface{}, variables interface{},
options ...graphql.Option, options ...graphql.Option,
) error { ) error {
if c.apiKey != "" { err := c.rl.Wait(ctx)
err := c.apirl.Wait(ctx) if err != nil {
if err != nil { return errors.Wrap(err, "waiting for rate limit")
return errors.Wrap(err, "waiting for rate limit")
}
} else {
err := c.rl.Wait(ctx)
if err != nil {
return errors.Wrap(err, "waiting for rate limit")
}
} }
c.lock.Lock() c.lock.Lock()
defer c.lock.Unlock() defer c.lock.Unlock()
@ -103,16 +86,9 @@ func (c *Client) QueryRaw(
variables interface{}, variables interface{},
options ...graphql.Option, options ...graphql.Option,
) ([]byte, error) { ) ([]byte, error) {
if c.apiKey != "" { err := c.rl.Wait(ctx)
err := c.apirl.Wait(ctx) if err != nil {
if err != nil { return nil, errors.Wrap(err, "waiting for rate limit")
return nil, errors.Wrap(err, "waiting for rate limit")
}
} else {
err := c.rl.Wait(ctx)
if err != nil {
return nil, errors.Wrap(err, "waiting for rate limit")
}
} }
c.lock.Lock() c.lock.Lock()
defer c.lock.Unlock() defer c.lock.Unlock()
@ -125,67 +101,11 @@ func (c *Client) Mutate(
variables interface{}, variables interface{},
options ...graphql.Option, options ...graphql.Option,
) error { ) error {
if c.apiKey != "" { err := c.rl.Wait(ctx)
err := c.apirl.Wait(ctx) if err != nil {
if err != nil { return errors.Wrap(err, "waiting for rate limit")
return errors.Wrap(err, "waiting for rate limit")
}
} else {
err := c.rl.Wait(ctx)
if err != nil {
return errors.Wrap(err, "waiting for rate limit")
}
} }
c.lock.Lock() c.lock.Lock()
defer c.lock.Unlock() defer c.lock.Unlock()
return c.gql.Mutate(ctx, q, variables, options...) return c.gql.Mutate(ctx, q, variables, options...)
} }
func GetTypeComplexity(t reflect.Type) int {
var checkStruct func(t reflect.Type, complexity *int)
checkStruct = func(t reflect.Type, complexity *int) {
if t.Kind() != reflect.Struct {
return
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
tag := field.Tag.Get("graphql")
if field.Type.Kind() == reflect.Struct {
*complexity++
if len(tag) > 6 && tag[:6] == "... on" {
*complexity--
}
checkStruct(field.Type, complexity)
continue
}
if field.Type.Kind() == reflect.Slice {
if isSimpleType(field.Type.Elem()) {
*complexity++
} else {
*complexity++
tmpcomplexity := 0
checkStruct(field.Type.Elem(), &tmpcomplexity)
*complexity += tmpcomplexity * 10
}
continue
}
if tag != "" && tag != "__typename" {
*complexity++
}
}
}
complexity := 0
checkStruct(t, &complexity)
return complexity
}
func isSimpleType(t reflect.Type) bool {
switch t.Kind() {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String:
return true
default:
return false
}
}

View File

@ -3,6 +3,8 @@ package graphql
import ( import (
"context" "context"
"reflect" "reflect"
"github.com/rs/zerolog/log"
) )
type PaginatedQuery[ResultType any, Params any] struct { type PaginatedQuery[ResultType any, Params any] struct {
@ -12,8 +14,6 @@ type PaginatedQuery[ResultType any, Params any] struct {
additionalPayloadParams map[string]interface{} additionalPayloadParams map[string]interface{}
additionalQueryParams map[string]interface{} additionalQueryParams map[string]interface{}
overrideComplexity int
} }
func NewPaginatedQuery[ResultType any, Params any]( func NewPaginatedQuery[ResultType any, Params any](
@ -27,7 +27,6 @@ func NewPaginatedQuery[ResultType any, Params any](
containerLayers: containerLayers, containerLayers: containerLayers,
additionalPayloadParams: make(map[string]interface{}), additionalPayloadParams: make(map[string]interface{}),
additionalQueryParams: make(map[string]interface{}), additionalQueryParams: make(map[string]interface{}),
overrideComplexity: 0,
} }
} }
@ -47,11 +46,6 @@ func (pq *PaginatedQuery[ResultType, Params]) WithQueryParam(
return pq return pq
} }
func (pq *PaginatedQuery[ResultType, Params]) WithOverrideComplexity(complexity int) *PaginatedQuery[ResultType, Params] {
pq.overrideComplexity = complexity
return pq
}
type PaginatedQueryGetOptions struct { type PaginatedQueryGetOptions struct {
Limit int Limit int
} }
@ -76,26 +70,18 @@ func (pq *PaginatedQuery[ResultType, Params]) Get(
var res []ResultType var res []ResultType
after := "" after := ""
var noop ResultType var noop ResultType
complexity := pq.overrideComplexity pageSize := (pq.c.MaxComplexity() - 9) / (GetComplexity(reflect.TypeOf(noop)) + 1)
if complexity == 0 { log.Debug().Msgf("using page size %d", pageSize)
complexity = GetTypeComplexity(reflect.TypeOf(noop))
}
maxPageSize := (pq.c.MaxQueryComplexity() - 7 - len(pq.containerLayers)) / complexity
for { for {
pageSize := maxPageSize
if opts.Limit > 0 {
remaining := opts.Limit - len(res)
if remaining < pageSize {
pageSize = remaining
}
}
page, pi, err := pq.getPage(ctx, params, after, pageSize) page, pi, err := pq.getPage(ctx, params, after, pageSize)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res = append(res, page...) for _, item := range page {
if opts.Limit > 0 && len(res) >= opts.Limit { res = append(res, item)
return res[:opts.Limit], nil if opts.Limit > 0 && len(res) >= opts.Limit {
return res, nil
}
} }
if !pi.HasNextPage { if !pi.HasNextPage {
break break
@ -139,3 +125,35 @@ func (pq *PaginatedQuery[ResultType, Params]) getPage(
} }
return res.Nodes, res.PageInfo, nil return res.Nodes, res.PageInfo, nil
} }
func GetComplexity(t reflect.Type) int {
var checkStruct func(t reflect.Type, complexity *int)
checkStruct = func(t reflect.Type, complexity *int) {
if t.Kind() != reflect.Struct {
return
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.Type.Kind() == reflect.Struct {
*complexity++
tag := field.Tag.Get("graphql")
if len(tag) > 6 && tag[:6] == "... on" {
*complexity--
}
checkStruct(field.Type, complexity)
continue
}
if field.Type.Kind() == reflect.Slice {
*complexity++
tmpcomplexity := 0
checkStruct(field.Type.Elem(), &tmpcomplexity)
*complexity += tmpcomplexity * 10
continue
}
*complexity++
}
}
complexity := 0
checkStruct(t, &complexity)
return complexity
}

View File

@ -3,7 +3,6 @@ package graphql
import ( import (
"context" "context"
"fmt" "fmt"
"reflect"
"strings" "strings"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -16,8 +15,6 @@ type Query[ReturnType any, Params any] struct {
additionalPayloadParams map[string]interface{} additionalPayloadParams map[string]interface{}
additionalQueryParams map[string]interface{} additionalQueryParams map[string]interface{}
maxPageSize int
} }
func NewQuery[ReturnType any, Params any]( func NewQuery[ReturnType any, Params any](
@ -32,7 +29,6 @@ func NewQuery[ReturnType any, Params any](
additionalPayloadParams: make(map[string]interface{}), additionalPayloadParams: make(map[string]interface{}),
additionalQueryParams: make(map[string]interface{}), additionalQueryParams: make(map[string]interface{}),
maxPageSize: 0,
} }
} }
@ -52,27 +48,6 @@ func (r *Query[ReturnType, Params]) WithQueryParam(
return r return r
} }
func (r *Query[ReturnType, Params]) WithMaxPageSize(maxPageSize int) *Query[ReturnType, Params] {
r.maxPageSize = maxPageSize
return r
}
func (r *Query[ReturnType, Params]) GetPageSize() int {
t := reflect.TypeOf((*ReturnType)(nil)).Elem()
if t.Kind() == reflect.Slice {
t = t.Elem()
}
complexity := GetTypeComplexity(t)
maxComplexity := r.c.MaxQueryComplexity()
layers := len(r.containerLayers)
computedPageSize := (maxComplexity - layers - 1) / complexity
if r.maxPageSize > 0 && r.maxPageSize < computedPageSize {
return r.maxPageSize
}
return computedPageSize
}
func (r *Query[ReturnType, Params]) Get(ctx context.Context, params Params) (ReturnType, error) { func (r *Query[ReturnType, Params]) Get(ctx context.Context, params Params) (ReturnType, error) {
paramsMap := convertParamsToMap(params) paramsMap := convertParamsToMap(params)

View File

@ -12,8 +12,8 @@ import (
) )
type baseUser struct { type baseUser struct {
Active bool `graphql:"active"` Active bool `graphql:"active"`
FootballCardCounts struct { CardCounts struct {
Common int `graphql:"common"` Common int `graphql:"common"`
CustomSeries int `graphql:"customSeries"` CustomSeries int `graphql:"customSeries"`
Limited int `graphql:"limited"` Limited int `graphql:"limited"`
@ -21,7 +21,7 @@ type baseUser struct {
SuperRare int `graphql:"superRare"` SuperRare int `graphql:"superRare"`
Unique int `graphql:"unique"` Unique int `graphql:"unique"`
Total int `graphql:"total"` Total int `graphql:"total"`
} `graphql:"footballCardCounts"` } `graphql:"cardCounts"`
CreatedAt time.Time `graphql:"createdAt"` CreatedAt time.Time `graphql:"createdAt"`
EthVaultId int `graphql:"ethVaultId"` EthVaultId int `graphql:"ethVaultId"`
EthereumAddress string `graphql:"ethereumAddress"` EthereumAddress string `graphql:"ethereumAddress"`