-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
841 lines (747 loc) · 22.5 KB
/
server.js
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
// JavaScript Document
'use strict';
var testingvar = 0;
restartServer();
function restartServer() {
//requires
require("babel-core").transform("code");
var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var path = require('path');
var querystring = require('querystring');
var async = require('async');
var cron = require('node-cron');
var fs = require('fs');
var AWS = require('aws-sdk');
var fetch = require('node-fetch');
require('heroku-self-ping')("https://tiltseeker.com/",{verbose: true});
//express module setup for calls
var app = express();
var currentTime = Date.now();
var deployTime = process.env.START_TIME;
var cacheTime = 86400000; // cache for 1 day
if (currentTime - deployTime >= cacheTime) {
app.use(express.static(__dirname + '/', { maxAge: cacheTime}));
console.log("caching");
} else {
app.use(express.static(__dirname + '/', { maxAge: 0}));
console.log("not caching");
setTimeout(function() {
console.log("restartingServer");
console.log(".");
console.log(".");
console.log(".");
console.log("~~~~~~~~~~~~~~~~~~~");
server.close();
restartServer();
}, cacheTime);
}
app.set('view engine', 'html');
//set AWS credentials
var s3 = new AWS.S3({
accessKeyId: process.env.AWSACCESSKEYID,
secretAccessKey: process.env.AWSSECRETACCESSKEY,
});
//set variables
var apikey = process.env.RIOTTILTSEEKERAPIKEY;
console.log(apikey);
var regions = ["na1", "euw1", "eun1", "br1", "tr1", "ru", "la1", "la2", "oc1", "kr", "jp1"];
var awsLoaded = false;
var adminMsg = "";
var awsSaving = false;
//sets up and loads the static champ data from Data Dragon and uses file as a backup
var staticChampData = [];
var apiVersion = "9.2.1"
getStaticChampData()
function getStaticChampData() {
let url = 'https://ddragon.leagueoflegends.com/api/versions.json';
fetch(url)
.then(res => res.json())
.then((versions) => {
apiVersion = versions[0]
let url = 'https://ddragon.leagueoflegends.com/cdn/' + apiVersion + '/data/en_US/champion.json';
fetch(url)
.then(res => res.json())
.then((theJSON) => {
staticChampData = theJSON
console.log("YAYAYAYA")
})
.catch(err => {
console.log("fail: Riot's Data Dragon service is down. Cannot fetch 'champion.json'.");
loadStaticChampData();
});
})
.catch(err => {
console.log("fail: Riot's Data Dragon service is down. Cannot fetch current game version.");
loadStaticChampData();
});
}
//loads savedMatches from file
//Edit: initialize savedMatches
var savedMatches = {"na1" : {}, "euw1" : {}, "eun1" : {}, "br1" : {}, "tr1" : {}, "ru" : {}, "la1" : {}, "la2" : {}, "oc1" : {}, "kr" : {}, "jp1" : {}};
//loadSavedMatches();
//Matches that need to be analyzed for stats data
var queuedMatches = [];
//stats data such as champion winrates, kda, etc.
var stats = {};
//loads stats from file
loadStats();
//stats averaged over multiple stat categories
var avgStats = {};
calcAvgStats();
//match IDs of matches that have been analyzed
var analyzedIds = [];
analyzedIds = stats.matchIds;
//start server
console.log(getMemory() + 'Listening on 8888');
var server = app.listen(process.env.PORT || 8888);
//cron schedules
//refresh staticChamp data for all regions every 15 minutes
cron.schedule('*/15 * * * *', function () {
getStaticChampData();
console.log(getMemory() + 'staticChamp data refreshed');
});
//save recorded matches to disk every 15 minutes
//cron.schedule('*/15 * * * *', function () {
// var totalGames = 0;
// for (var i = 0; i < regions.length; i++) {
// writeSavedMatches(regions[i]);
// totalGames += Object.keys(savedMatches[regions[i]]).length;
// }
// console.log('Matches saved to disk. Total: ' + totalGames);
//});
//save stats to AWS once an hour if stats have been previously loaded
cron.schedule('0 * * * *', function () {
awsSaving = true;
//delay for current stats writes to finish before saving
setTimeout(saveStats,5000);
});
//if stats failed to load, retries once an hour
cron.schedule('30 * * * *', function () {
loadStats();
});
//recalculate average stats every 24 hours
cron.schedule('10 0 * * *', function () {
calcAvgStats();
});
//check if queued matches is too long and needs to be analyzed every 20 seconds
//matches are 0.05 MB each
cron.schedule('*/20 * * * * *', function () {
if (queuedMatches.length > 10) {
//makes a new timestamp if more than 24 hours have passed 1000 ms * 60 sec * 60 min * 24 hr
analyzeMatches(new Date().getTime() - Object.keys(stats)[Object.keys(stats).length-1] < 1000 * 60 * 60 * 24);
}
});
//prunes savedMatches to a maximum length every 1 minute
//matches are 0.05 MB each
cron.schedule('*/20 * * * * *', function () {
var maxSize = 1000;
var currentSize = Object.keys(savedMatches["na1"]).length;
if (currentSize > maxSize) {
var theKeys = Object.keys(savedMatches["na1"]).slice(0,currentSize - maxSize);
for (var i = 0; i < theKeys.length; i++) {
delete savedMatches["na1"][theKeys[i]];
}
console.log(getMemory() + "savedMatches have been pruned");
}
});
//API call limiters
var callList1 = [];
var maxCalls1 = 1500;
var perTimeMs1 = 10000;
var callList2 = [];
var maxCalls2 = 90000;
var perTimeMs2 = 600000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function apiLimit1(req, res, next) {
var theTime = (new Date()).getTime();
if (callList1.length < maxCalls1) {
callList1.push(theTime);
next();
} else if (callList1.length >= maxCalls1 && callList1[0] < theTime - perTimeMs1) {
callList1.push(theTime);
callList1.shift();
next();
} else {
await sleep(theTime-callList1[0]);
apiLimit1(req, res, next);
}
}
async function apiLimit2(req, res, next) {
var theTime = (new Date()).getTime();
if (callList2.length < maxCalls2) {
callList2.push(theTime);
next();
} else if (callList2.length >= maxCalls2 && callList2[0] < theTime - perTimeMs2) {
callList2.push(theTime);
callList2.shift();
next();
} else {
var tempDelay = theTime-callList2[0];
console.log(getMemory() + "API rate limit reached. Waiting " + tempDelay + "ms");
await sleep(tempDelay);
apiLimit2(req, res, next);
}
}
//filter for getMatch to check for local match data first
function getMatchFilter(req, res, next) {
var theMatch = savedMatches[req.query.region][req.query.matchId];
if (theMatch) {
res.send(theMatch);
return;
} else {
next();
}
}
//apply API limits to all direct API requests
app.use(/\/summonerByName|\/currentGame|\/getChampList|\/matchList|\/getMastery|\/getLeague/,apiLimit1, apiLimit2);
//apply API limits with local check to getMatch requests
app.use('/getMatch', getMatchFilter, apiLimit1, apiLimit2);
//local file loads and writes
//loads file data into staticChampData variable
function loadStaticChampData() {
var rawdata = fs.readFileSync('staticData/staticChamp.json');
var staticChamp = JSON.parse(rawdata);
staticChampData = staticChamp;
}
//updates a staticChamp json file
function refreshStaticChamp() {
var URL = "https://ddragon.leagueoflegends.com/cdn/" + apiVersion + "/data/en_US/champion.json";
var filePath = 'staticData/staticChamp.json';
//ensures that a filepath exists
ensureDirectoryExistence(filePath);
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
return async.waterfall([
function (callback) {
request(URL, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
callback(null, json);
} else {
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
console.log("No Response");
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
return {
"error": err
};
return;
}
//update and write staticChamp to file
var theFile = 'staticData/staticChamp.json';
var data = JSON.stringify(data, null, 2);
fs.writeFileSync(theFile, data);
return data;
});
}
//loads file data into savedMatches variable
function loadSavedMatches() {
for (var i = 0; i < regions.length; i++) {
var rawdata = fs.readFileSync('matchData/' + regions[i] + '/matchData.json');
var savedMatchesRegion = JSON.parse(rawdata);
savedMatches[regions[i]] = savedMatchesRegion;
}
}
//writes savedMatches to file
function writeSavedMatches(region) {
var theFile = 'matchData/' + region + '/matchData.json';
var data = JSON.stringify(savedMatches[region], null, 2);
fs.writeFileSync(theFile, data);
}
//loads stats from AWS
function loadStats() {
if (!awsLoaded) {
var params = {
Bucket: "tiltseeker",
Key: "statsData.json",
};
s3.getObject(params, function (err, data) {
if (err) {
console.log(err, err.stack);
} else {
var rawdata = data.Body.toString();
stats = JSON.parse(rawdata);
awsLoaded = true;
console.log(getMemory() + "AWS loaded");
calcAvgStats();
analyzedIds = stats.matchIds;
}
});
}
}
//saves stats to AWS
function saveStats() {
if (awsLoaded && process.env.DEV_OR_PRODUCTION == "production") {
var stream = fs.createReadStream(__dirname + "/stats/statsData.json");
var params = {
Bucket: "tiltseeker",
Key: "statsData.json",
Body: stream,
};
s3.upload(params, function(err, data) {
if (err) {
console.log(getMemory() + "AWS error:" + err);
awsSaving = false;
} else {
console.log(getMemory() + "AWS saved");
awsSaving = false;
}
});
} else {
console.log("AWS not saved. Load status:" + awsLoaded);
awsSaving = false;
}
if (process.env.DEV_OR_PRODUCTION != "production") {
console.log("AWS not saved in development");
}
}
//writes stats variable to file
function writeStats() {
if (!awsSaving) {
var theFile = 'stats/statsData.json';
var data = JSON.stringify(stats, null, 2);
fs.writeFileSync(theFile, data);
} else {
console.log("Stats not written while uploading to AWS");
}
}
//analyze queued match data and add analysis to stats file
function analyzeMatches(early = false) {
var timestamp;
//get time in epoch milliseconds
if (early == false) {
timestamp = new Date().getTime();
stats[timestamp] = {};
} else {
//if an early update, add to the previous timestamp
timestamp = Object.keys(stats)[Object.keys(stats).length - 1];
//check if previous timestamp exists
if (isNaN(timestamp)) {
timestamp = new Date().getTime();
stats[timestamp] = {};
}
}
//adds matchCount key if it does not exist
if (stats[timestamp].matchCount == undefined) {
stats[timestamp].matchCount = 0;
}
//iterate through matches
for (var theMatch in queuedMatches) {
//check if map is summoners rift and skips if it isn't
if (queuedMatches[theMatch].mapId != 11) {continue;}
//checks if the match has been analyzed yet and skips if it has
if (analyzedIds.indexOf(queuedMatches[theMatch].gameId) != -1) {
continue;
} else {
analyzedIds.push(queuedMatches[theMatch].gameId);
}
//increment matchCount
stats[timestamp].matchCount += 1;
//iterate through each champion's game stats
for (var j = 0; j < queuedMatches[theMatch].participants.length; j++) {
var theChamp = queuedMatches[theMatch].participants[j].championId;
//check if stats for champ exists yet
if (stats[timestamp][theChamp] && stats[timestamp][theChamp].total) {
stats[timestamp][theChamp].total = stats[timestamp][theChamp].total + 1;
addStats(stats[timestamp][theChamp], queuedMatches[theMatch].participants[j].stats);
} else if (stats[timestamp][theChamp]) {
stats[timestamp][theChamp].total = 1;
addStats(stats[timestamp][theChamp], queuedMatches[theMatch].participants[j].stats);
} else {
stats[timestamp][theChamp] = {};
stats[timestamp][theChamp].total = 1;
addStats(stats[timestamp][theChamp], queuedMatches[theMatch].participants[j].stats);
}
}
}
//add stats for the match to permanant storage
function addStats(savedStats, matchStats) {
if (savedStats.win != undefined) {
savedStats.win += matchStats.win ? 1 : 0;
} else {
savedStats.win = matchStats.win ? 1 : 0;
}
//combine first tower kill and first tower assist
if (savedStats.firstTowerParticipate != undefined) {
savedStats.firstTowerParticipate += (matchStats.firstTowerKill || matchStats.firstTowerAssist) ? 1 : 0;
} else {
savedStats.firstTowerParticipate = matchStats.win ? 1 : 0;
}
//Champion damage stats
if (savedStats.magicDamage != undefined) {
savedStats.magicDamage += matchStats.magicDamageDealtToChampions;
} else {
savedStats.magicDamage = matchStats.magicDamageDealtToChampions;
}
if (savedStats.physicalDamage != undefined) {
savedStats.physicalDamage += matchStats.physicalDamageDealtToChampions;
} else {
savedStats.physicalDamage = matchStats.physicalDamageDealtToChampions;
}
if (savedStats.trueDamage != undefined) {
savedStats.trueDamage += matchStats.trueDamageDealtToChampions;
} else {
savedStats.trueDamage = matchStats.trueDamageDealtToChampions;
}
if (savedStats.kills != undefined) {
savedStats.kills += matchStats.kills;
} else {
savedStats.kills = matchStats.kills;
}
if (savedStats.deaths != undefined) {
savedStats.deaths += matchStats.deaths;
} else {
savedStats.deaths = matchStats.deaths;
}
if (savedStats.assists != undefined) {
savedStats.assists += matchStats.assists;
} else {
savedStats.assists = matchStats.assists;
}
if (savedStats.wardsPlaced != undefined) {
savedStats.wardsPlaced += matchStats.wardsPlaced;
} else {
savedStats.wardsPlaced = matchStats.wardsPlaced;
}
}
console.log(getMemory() + "Analyzed " + queuedMatches.length + " matches");
//clear matches queue
queuedMatches = [];
//store analyzedIds in json
stats.matchIds = analyzedIds;
//write stats to file
writeStats();
}
//averages stats over multiple timestamps
function calcAvgStats() {
// 3 WEEKS: 1000ms * 60sec * 60min * 24hrs * 21days
var historyLength = 1000 * 60 * 60 * 24 * 21
var currentTime = (new Date()).getTime();
var theTimes = Object.keys(stats);
for (var i = theTimes.length - 1; i >= 0; i--) {
//skip if not a timestamp
if (isNaN(theTimes[i])) {continue;}
if (avgStats.matchCount == null) {avgStats.matchCount = 0;}
avgStats.matchCount += stats[theTimes[i]].matchCount;
console.log(currentTime - theTimes[i])
if (currentTime - theTimes[i] > historyLength) {break;}
var listChamps = Object.keys(stats[theTimes[i]]);
for (var j = 0; j < listChamps.length; j++) {
var theStats = Object.keys(stats[theTimes[i]][listChamps[j]]);
if (avgStats[listChamps[j]] == null) {avgStats[listChamps[j]] = {};}
for (var k = 0; k < theStats.length; k++) {
if (avgStats[listChamps[j]][theStats[k]] == null) {avgStats[listChamps[j]][theStats[k]] = 0;}
avgStats[listChamps[j]][theStats[k]] += stats[theTimes[i]][listChamps[j]][theStats[k]];
}
}
}
console.log(theTimes.length);
}
//returns system memory in use
function getMemory() {return Math.round(process.memoryUsage().rss/(1024*1024)*10)/10 + "MB: ";}
//client call listeners
//call to get a summoner's info by summoner name
app.get('/summonerByName', function (req, res) {
if (regions.indexOf(req.query.region) == -1) {
res.send({
"error": 778
});
return;
}
var URL = "https://" + req.query.region + ".api.riotgames.com/lol/summoner/v4/summoners/by-name/" + querystring.escape(req.query.username) + "?api_key=" + apikey;
async.waterfall([
function myFunction(callback, attempt = 0) {
request({uri: URL,timeout: 1500}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
json.name = decodeURIComponent(json.name);
callback(null, json);
} else {
//check if server responded
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
if (attempt >= 3) {
callback(777, JSON.parse("{}"));
} else {
console.log("empty response");
myFunction(callback, attempt + 1);
}
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
res.send({
"error": err
});
return;
}
res.send(data);
});
});
//call to get the current game of a summoner by summonerId
app.get('/currentGame', function (req, res) {
if (regions.indexOf(req.query.region) == -1) {
res.send({
"error": 778
});
return;
}
var URL = "https://" + req.query.region + ".api.riotgames.com/lol/spectator/v4/active-games/by-summoner/" + req.query.summonerId + "?api_key=" + apikey;
async.waterfall([
function myFunction(callback, attempt = 0) {
request({uri: URL,timeout: 1500}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
callback(null, json);
} else {
//check if server responded
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
if (attempt >= 3) {
callback(777, JSON.parse("{}"));
} else {
console.log("empty response");
myFunction(callback, attempt + 1);
}
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
res.send({
"error": err
});
return;
}
res.send(data);
});
});
//updates a staticChamp json file
app.get('/getChampList', function (req, res) {
req.query.region;
res.send(staticChampData);
});
//returns the admin message
app.get('/adminMsg', function (req, res) {
res.send(adminMsg);
});
//returns the admin message
app.get('/setAdminMsg', function (req, res) {
if (req.query.pass == process.env.ADMIN_PASS) {
adminMsg = req.query.message;
console.log("Admin Message: " + adminMsg);
res.send("1");
} else {
res.send("0");
}
});
//returns the stats file with just requested champions
app.get('/getStats', function (req, res) {
var champIdList = req.query.champList;
var tempStats = {};
tempStats.matchCount = avgStats.matchCount;
for (var i = 0; i < champIdList.length; i++) {
tempStats[champIdList[i]] = avgStats[champIdList[i]];
}
res.send(tempStats);
});
//call to get a match list history for a summoner
app.get('/matchList', function (req, res) {
if (regions.indexOf(req.query.region) == -1) {
res.send({
"error": 778
});
return;
}
//summoners rift only
var URL = "https://" + req.query.region + ".api.riotgames.com/lol/match/v4/matchlists/by-account/" + req.query.accountId + "?queue=400&queue=420&queue=430&queue=440&api_key=" + apikey;
async.waterfall([
function myFunction(callback, attempt = 0) {
request({uri: URL,timeout: 1500}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
callback(null, json);
} else {
//check if server responded
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
if (attempt >= 3) {
callback(777, JSON.parse("{}"));
} else {
console.log("empty response");
myFunction(callback, attempt + 1);
}
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
res.send({
"error": err
});
return;
}
res.send(data);
});
});
//call to get match info
app.get('/getMatch', function (req, res) {
if (regions.indexOf(req.query.region) == -1) {
res.send({
"error": 778
});
return;
}
var URL = "https://" + req.query.region + ".api.riotgames.com/lol/match/v4/matches/" + req.query.matchId + "?api_key=" + apikey;
async.waterfall([
function myFunction(callback, attempt = 0) {
request({uri: URL,timeout: 1500}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
savedMatches[req.query.region][req.query.matchId] = json;
queuedMatches.push(json);
callback(null, json);
} else {
//check if server responded
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
if (attempt >= 3) {
callback(777, JSON.parse("{}"));
} else {
console.log("empty response");
myFunction(callback, attempt + 1);
}
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
res.send({
"error": err
});
return;
}
res.send(data);
});
});
//call to get a summoner's mastery on a champion
app.get('/getMastery', function (req, res) {
if (regions.indexOf(req.query.region) == -1) {
res.send({
"error": 778
});
return;
}
var URL = "https://" + req.query.region + ".api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/" + req.query.summonerId + "/by-champion/" + req.query.championId + "?api_key=" + apikey;
async.waterfall([
function myFunction(callback, attempt = 0) {
request({uri: URL,timeout: 1500}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
json.name = decodeURIComponent(json.name);
callback(null, json);
} else {
//check if server responded
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
if (attempt >= 3) {
callback(777, JSON.parse("{}"));
} else {
console.log("empty response");
myFunction(callback, attempt + 1);
}
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
res.send({
"error": err
});
return;
}
res.send(data);
});
});
//call to get a summoner's ranked league stats
app.get('/getLeague', function (req, res) {
if (regions.indexOf(req.query.region) == -1) {
res.send({
"error": 778
});
return;
}
var URL = "https://" + req.query.region + ".api.riotgames.com/lol/league/v4/entries/by-summoner/" + req.query.summonerId + "?api_key=" + apikey;
async.waterfall([
function myFunction(callback, attempt = 0) {
request({uri: URL,timeout: 1500}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
json.name = decodeURIComponent(json.name);
callback(null, json);
} else {
//check if server responded
if (response) {
callback(response.statusCode, JSON.parse(body));
} else {
if (attempt >= 3) {
callback(777, JSON.parse("{}"));
} else {
console.log("empty response");
myFunction(callback, attempt + 1);
}
}
}
});
}
],
function (err, data) {
if (err) {
console.log(getMemory() + err);
res.send({
"error": err
});
return;
}
res.send(data);
});
});
}