-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathdata_dragon.go
437 lines (410 loc) · 11.6 KB
/
data_dragon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Package datadragon provides methods for retrieving data from the DataDragon API.
// This data is only updated for every new version of League of Legends.
package datadragon
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
log "github.com/sirupsen/logrus"
"github.com/KnutZuidema/golio/api"
"github.com/KnutZuidema/golio/internal"
)
const (
latestRuneAndMasteryVersion = "7.23.1"
fallbackVersion = "9.10.1"
fallbackLanguage = LanguageCodeUnitedStates
)
var (
regionToRealmRegion = map[api.Region]string{
api.RegionEuropeWest: "euw",
api.RegionEuropeNorthEast: "eun",
api.RegionJapan: "jp",
api.RegionKorea: "kr",
api.RegionLatinAmericaNorth: "lan",
api.RegionLatinAmericaSouth: "las",
api.RegionNorthAmerica: "na",
api.RegionOceania: "oce",
api.RegionPBE: "pbe",
api.RegionRussia: "ru",
api.RegionTurkey: "tr",
api.RegionBrasil: "br",
}
)
// Client provides access to all data provided by the Data Dragon service
type Client struct {
logger log.FieldLogger
Version string
Language languageCode
client internal.Doer
championsMu sync.RWMutex
championsByName map[string]ChampionDataExtended
getChampionsToggle uint32
profileIconsMu sync.RWMutex
profileIcons []ProfileIcon
itemsMu sync.RWMutex
items []Item
masteriesMu sync.RWMutex
masteries []Mastery
runesMu sync.RWMutex
runes []Item
summonersMu sync.RWMutex
summoners []SummonerSpell
}
// NewClient returns a new client for the Data Dragon service.
func NewClient(client internal.Doer, region api.Region, logger log.FieldLogger) *Client {
c := &Client{
client: client,
logger: logger.WithField("client", "data dragon"),
championsByName: map[string]ChampionDataExtended{},
}
if err := c.init(regionToRealmRegion[region]); err != nil {
c.Version = fallbackVersion
c.Language = fallbackLanguage
}
return c
}
func (c *Client) init(region string) error {
var res struct {
Version string `json:"v"`
Language string `json:"l"`
}
response, err := c.doRequest(dataDragonBaseURL, fmt.Sprintf("/realms/%s.json", region))
if err != nil {
return err
}
if response.Body == nil {
return fmt.Errorf("no response body")
}
if err := json.NewDecoder(response.Body).Decode(&res); err != nil {
return err
}
c.Version = res.Version
c.Language = languageCode(res.Language)
return nil
}
// GetChampions returns all existing champions
func (c *Client) GetChampions() ([]ChampionData, error) {
unlock, toggle := internal.RWLockToggle(&c.championsMu)
defer unlock()
if atomic.CompareAndSwapUint32(&c.getChampionsToggle, 0, 1) {
toggle()
var champions map[string]ChampionData
if err := c.getInto("/champion.json", &champions); err != nil {
return nil, err
}
for _, champion := range champions {
data := ChampionDataExtended{ChampionData: champion}
c.championsByName[champion.Name] = data
}
}
res := make([]ChampionData, 0, len(c.championsByName))
for _, champion := range c.championsByName {
res = append(res, champion.ChampionData)
}
return res, nil
}
// GetChampionByID returns information about the champion with the given id
func (c *Client) GetChampionByID(id string) (ChampionDataExtended, error) {
champions, err := c.GetChampions()
if err != nil {
return ChampionDataExtended{}, err
}
for _, champion := range champions {
if champion.ID == id {
return c.GetChampion(champion.Name)
}
}
return ChampionDataExtended{}, api.ErrNotFound
}
// GetChampion returns information about the champion with the given name
func (c *Client) GetChampion(name string) (ChampionDataExtended, error) {
unlock, toggle := internal.RWLockToggle(&c.championsMu)
defer unlock()
champion, ok := c.championsByName[name]
if !ok || champion.Lore == "" {
toggle()
var data map[string]ChampionDataExtended
if err := c.getInto(fmt.Sprintf("/champion/%s.json", name), &data); err != nil {
return ChampionDataExtended{}, err
}
champion, ok = data[name]
if !ok {
return ChampionDataExtended{}, api.ErrNotFound
}
c.championsByName[name] = champion
}
return champion, nil
}
// GetProfileIcons returns all existing profile icons
func (c *Client) GetProfileIcons() ([]ProfileIcon, error) {
unlock, toggle := internal.RWLockToggle(&c.profileIconsMu)
defer unlock()
if len(c.profileIcons) < 1 {
toggle()
var res map[string]ProfileIcon
if err := c.getInto("/profileicon.json", &res); err != nil {
return nil, err
}
c.profileIcons = make([]ProfileIcon, 0, len(res))
for _, profileIcon := range res {
c.profileIcons = append(c.profileIcons, profileIcon)
}
}
res := make([]ProfileIcon, len(c.profileIcons))
copy(res, c.profileIcons)
return res, nil
}
// GetProfileIcon return information about the profile icon with the given id
func (c *Client) GetProfileIcon(id int) (ProfileIcon, error) {
icons, err := c.GetProfileIcons()
if err != nil {
return ProfileIcon{}, err
}
for _, icon := range icons {
if icon.ID == id {
return icon, nil
}
}
return ProfileIcon{}, api.ErrNotFound
}
// GetItems returns all existing items
func (c *Client) GetItems() ([]Item, error) {
unlock, toggle := internal.RWLockToggle(&c.itemsMu)
defer unlock()
if len(c.items) < 1 {
toggle()
var res map[string]Item
if err := c.getInto("/item.json", &res); err != nil {
return nil, err
}
c.items = make([]Item, 0, len(res))
for id, item := range res {
item.ID = id
c.items = append(c.items, item)
}
}
res := make([]Item, len(c.items))
copy(res, c.items)
return res, nil
}
// GetItem return information about the item with the given id
func (c *Client) GetItem(id string) (Item, error) {
items, err := c.GetItems()
if err != nil {
return Item{}, err
}
for _, item := range items {
if item.ID == id {
return item, nil
}
}
return Item{}, api.ErrNotFound
}
// GetMasteries returns all existing masteries. Masteries were removed in patch 7.23.1. If any version higher than that
// is specified the last available version will be used instead.
func (c *Client) GetMasteries() ([]Mastery, error) {
unlock, toggle := internal.RWLockToggle(&c.masteriesMu)
defer unlock()
if len(c.masteries) < 1 {
toggle()
var res map[string]Mastery
if err := c.getInto("/mastery.json", &res); err != nil {
return nil, err
}
c.masteries = make([]Mastery, 0, len(res))
for _, mastery := range res {
c.masteries = append(c.masteries, mastery)
}
}
res := make([]Mastery, len(c.masteries))
copy(res, c.masteries)
return res, nil
}
// GetMastery returns information about the mastery with the given id
func (c *Client) GetMastery(id int) (Mastery, error) {
masteries, err := c.GetMasteries()
if err != nil {
return Mastery{}, err
}
for _, mastery := range masteries {
if mastery.ID == id {
return mastery, nil
}
}
return Mastery{}, api.ErrNotFound
}
// GetRunes returns all existing runes. Runes were removed in patch 7.23.1. If any version higher than that
// is specified the last available version will be used instead.
func (c *Client) GetRunes() ([]Item, error) {
unlock, toggle := internal.RWLockToggle(&c.runesMu)
defer unlock()
if len(c.runes) < 1 {
toggle()
var res map[string]Item
if err := c.getInto("/rune.json", &res); err != nil {
return nil, err
}
c.runes = make([]Item, 0, len(res))
for id, runeItem := range res {
runeItem.ID = id
c.runes = append(c.runes, runeItem)
}
}
res := make([]Item, len(c.runes))
copy(res, c.runes)
return res, nil
}
// GetRune returns information about the rune with the given id
func (c *Client) GetRune(id string) (Item, error) {
runes, err := c.GetRunes()
if err != nil {
return Item{}, err
}
for _, r := range runes {
if r.ID == id {
return r, nil
}
}
return Item{}, api.ErrNotFound
}
// GetSummonerSpells returns all existing summoner spells
func (c *Client) GetSummonerSpells() ([]SummonerSpell, error) {
unlock, toggle := internal.RWLockToggle(&c.summonersMu)
defer unlock()
if len(c.summoners) < 1 {
toggle()
var res map[string]SummonerSpell
if err := c.getInto("/summoner.json", &res); err != nil {
return nil, err
}
c.summoners = make([]SummonerSpell, 0, len(res))
for _, summoner := range res {
c.summoners = append(c.summoners, summoner)
}
}
res := make([]SummonerSpell, len(c.summoners))
copy(res, c.summoners)
return res, nil
}
// GetSummonerSpell returns information about the summoner spell with the given id
func (c *Client) GetSummonerSpell(id string) (SummonerSpell, error) {
summonerSpells, err := c.GetSummonerSpells()
if err != nil {
return SummonerSpell{}, err
}
for _, summonerSpell := range summonerSpells {
if summonerSpell.ID == id {
return summonerSpell, nil
}
}
return SummonerSpell{}, api.ErrNotFound
}
// ClearCaches resets all caches of the data dragon client
func (c *Client) ClearCaches() {
c.championsMu.Lock()
c.championsByName = map[string]ChampionDataExtended{}
atomic.StoreUint32(&c.getChampionsToggle, 0)
c.championsMu.Unlock()
c.masteriesMu.Lock()
c.masteries = []Mastery{}
c.masteriesMu.Unlock()
c.profileIconsMu.Lock()
c.profileIcons = []ProfileIcon{}
c.profileIconsMu.Unlock()
c.itemsMu.Lock()
c.items = []Item{}
c.itemsMu.Unlock()
c.summonersMu.Lock()
c.summoners = []SummonerSpell{}
c.summonersMu.Unlock()
c.runesMu.Lock()
c.runes = []Item{}
c.runesMu.Unlock()
}
func (c *Client) getInto(endpoint string, target interface{}) error {
response, err := c.doRequest(dataDragonDataURLFormat, endpoint)
if err != nil {
return err
}
var ddResponse dataDragonResponse
if err = json.NewDecoder(response.Body).Decode(&ddResponse); err != nil {
return err
}
// this can not return an error. the error would have been returned during the above decode already
data, _ := json.Marshal(ddResponse.Data)
return json.Unmarshal(data, &target)
}
func (c *Client) doRequest(format dataDragonURL, endpoint string) (*http.Response, error) {
request, err := c.newRequest(format, endpoint)
if err != nil {
return nil, err
}
response, err := c.client.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode < 200 || response.StatusCode > 299 {
var err error
err, ok := api.StatusToError[response.StatusCode]
if !ok {
err = api.Error{
Message: "unknown error reason",
StatusCode: response.StatusCode,
}
}
return nil, err
}
return response, nil
}
func (c *Client) newRequest(format dataDragonURL, endpoint string) (*http.Request, error) {
var version string
if (strings.Contains(endpoint, "rune") || strings.Contains(endpoint, "mastery")) &&
versionGreaterThan(c.Version, latestRuneAndMasteryVersion) {
version = latestRuneAndMasteryVersion
} else {
version = c.Version
}
var url string
switch format {
case dataDragonDataURLFormat:
url = fmt.Sprintf(string(format), version, c.Language)
case dataDragonImageURLFormat:
url = fmt.Sprintf(string(format), version)
default:
url = string(format)
}
url = "https://" + url + endpoint
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return request, nil
}
func versionGreaterThan(v1, v2 string) bool {
v1Split := strings.Split(v1, ".")
v2Split := strings.Split(v2, ".")
for i := 0; i < len(v1Split) && i < len(v2Split); i++ {
int1, err := strconv.Atoi(v1Split[i])
if err != nil {
return false
}
int2, err := strconv.Atoi(v2Split[i])
if err != nil {
return false
}
if int1 > int2 {
return true
}
}
return false
}
type dataDragonResponse struct {
Type string
Format string
Version string
Data interface{}
}