forked from odota/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.js
422 lines (410 loc) · 13.8 KB
/
utility.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
var request = require('request');
var winston = require('winston');
var config = require('./config');
var BigNumber = require('big-number').n;
var urllib = require('url');
var transports = [];
transports.push(new(winston.transports.Console)({
'timestamp': true
}));
var logger = new(winston.Logger)({
transports: transports
});
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize(input) {
return input.replace(/[^a-zA-Z- ]+/g, '').replace('/ {2,}/', ' ').toLowerCase().split(' ');
}
function generateJob(type, payload) {
var api_url = "http://api.steampowered.com";
var api_key;
var opts = {
"api_details": function() {
return {
url: api_url + "/IDOTA2Match_570/GetMatchDetails/V001/?key=" + api_key + "&match_id=" + payload.match_id,
title: [type, payload.match_id].join(),
type: "api",
payload: payload
};
},
"api_history": function() {
return {
url: api_url + "/IDOTA2Match_570/GetMatchHistory/V001/?key=" + api_key + (payload.account_id ? "&account_id=" + payload.account_id : "") + (payload.matches_requested ? "&matches_requested=" + payload.matches_requested : "") + (payload.hero_id ? "&hero_id=" + payload.hero_id : "") + (payload.leagueid ? "&league_id=" + payload.leagueid : ""),
title: [type, payload.account_id].join(),
type: "api",
payload: payload
};
},
"api_summaries": function() {
return {
url: api_url + "/ISteamUser/GetPlayerSummaries/v0002/?key=" + api_key + "&steamids=" + payload.players.map(function(p) {
return convert32to64(p.account_id).toString();
}).join(),
title: [type, payload.summaries_id].join(),
type: "api",
payload: payload
};
},
"api_sequence": function() {
return {
url: api_url + "/IDOTA2Match_570/GetMatchHistoryBySequenceNum/V001/?key=" + api_key + "&start_at_match_seq_num=" + payload.start_at_match_seq_num,
title: [type, payload.seq_num].join(),
type: "api"
};
},
"api_heroes": function() {
return {
url: api_url + "/IEconDOTA2_570/GetHeroes/v0001/?key=" + api_key + "&language=" + payload.language,
title: [type, payload.language].join(),
type: "api",
payload: payload
};
},
"api_leagues": function() {
return {
url: api_url + "/IDOTA2Match_570/GetLeagueListing/v0001/?key=" + api_key,
title: [type].join(),
type: "api",
payload: payload
};
},
"api_skill": function() {
return {
url: api_url + "/IDOTA2Match_570/GetMatchHistory/v0001/?key=" + api_key + "&start_at_match_id=" + payload.start_at_match_id + "&skill=" + payload.skill + "&hero_id=" + payload.hero_id + "&min_players=10",
title: [type, payload.skill].join(),
type: "api",
payload: payload
};
},
"api_live": function() {
return {
url: api_url + "/IDOTA2Match_570/GetLiveLeagueGames/v0001/?key=" + api_key,
title: [type].join(),
type: "api",
payload: payload
};
},
"parse": function() {
return {
title: [type, payload.match_id].join(),
type: type,
fileName: payload.fileName,
url: payload.url,
payload: payload
};
},
"request": function() {
payload.attempts = 1;
return {
url: api_url + "/IDOTA2Match_570/GetMatchDetails/V001/?key=" + api_key + "&match_id=" + payload.match_id,
title: [type, payload.match_id].join(),
type: type,
payload: payload
};
},
"fullhistory": function() {
payload.attempts = 1;
return {
title: [type, payload.account_id].join(),
type: type,
payload: payload
};
},
"shorthistory": function() {
payload.attempts = 1;
return {
title: [type, payload.account_id].join(),
type: type,
short_history: true,
payload: payload
};
},
"mmr": function() {
payload.attempts = 1;
return {
title: [type, payload.match_id, payload.account_id].join(),
type: type,
url: payload.url,
payload: payload
};
}
};
return opts[type]();
}
function getData(url, cb) {
var u;
if (url.constructor === Array) {
//select a random element if array
u = url[Math.floor(Math.random() * url.length)];
}
else if (typeof url === "object") {
//options object
u = url.url;
}
else {
u = url;
}
var parse = urllib.parse(u, true);
var proxy;
var steam_api = false;
if (parse.host === "api.steampowered.com") {
steam_api = true;
//choose an api key to use
var api_keys = config.STEAM_API_KEY.split(",");
parse.query.key = api_keys[Math.floor(Math.random() * api_keys.length)];
parse.search = null;
/*
//choose a proxy to request through
var proxies = config.PROXY_URLS.split(",");
//add no proxy option
proxies.push(null);
proxy = proxies[Math.floor(Math.random() * proxies.length)];
console.log(proxies, proxy);
*/
//choose a steam api host
var api_hosts = config.STEAM_API_HOST.split(",");
parse.host = api_hosts[Math.floor(Math.random() * api_hosts.length)];
}
var target = urllib.format(parse);
logger.info("getData: %s", target);
var delay = 1000;
return setTimeout(function() {
request({
proxy: proxy,
url: target,
json: true,
timeout: 30000
}, function(err, res, body) {
if (body && body.error) {
//body contained specific error (probably from retriever)
//non-retryable
return cb(body);
}
if (err || res.statusCode !== 200 || !body || (steam_api && !body.result && !body.response)) {
//invalid response
if (url.noRetry) {
return cb(err || "invalid response");
}
else {
logger.info("invalid response, retrying: %s", target);
return getData(url, cb);
}
}
else if (body.result) {
//steam api usually returns data with body.result, getplayersummaries has body.response
if (body.result.status === 15 || body.result.error === "Practice matches are not available via GetMatchDetails" || body.result.error === "No Match ID specified" || body.result.error === "Match ID not found") {
//user does not have stats enabled or attempting to get private match/invalid id, don't retry
//non-retryable
return cb(body);
}
else if (body.result.error || body.result.status === 2) {
//valid response, but invalid data, retry
if (url.noRetry) {
return cb(err || "invalid data");
}
else {
logger.info("invalid data, retrying: %s, %s", target, JSON.stringify(body));
return getData(url, cb);
}
}
}
return cb(null, body);
});
}, delay);
}
/*
* Converts a steamid 64 to a steamid 32
*
* Returns a BigNumber
*/
function convert64to32(id) {
return new BigNumber(id).minus('76561197960265728');
}
/*
* Converts a steamid 64 to a steamid 32
*
* Returns a BigNumber
*/
function convert32to64(id) {
return new BigNumber('76561197960265728').plus(id);
}
function isRadiant(player) {
return player.player_slot < 127;
}
function mergeObjects(merge, val) {
for (var attr in val) {
//does property exist?
if (!merge[attr]) {
merge[attr] = val[attr];
}
else if (val[attr].constructor === Array) {
merge[attr] = merge[attr].concat(val[attr]);
}
else if (typeof val[attr] === "object") {
mergeObjects(merge[attr], val[attr]);
}
else {
merge[attr] += val[attr];
}
}
}
function mode(array) {
if (array.length == 0) return null;
var modeMap = {};
var maxEl = array[0],
maxCount = 1;
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (modeMap[el] == null) modeMap[el] = 1;
else modeMap[el]++;
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
function getParseSchema() {
return {
"version": 12,
"match_id": 0,
"teamfights": [],
"objectives": [],
"chat": [],
"radiant_gold_adv": [],
"radiant_xp_adv": [],
"players": Array.apply(null, new Array(10)).map(function() {
return {
"steam_id": "",
"stuns": 0,
"max_hero_hit": {
value: 0
},
"times": [],
"gold": [],
"lh": [],
"xp": [],
//"pos_log": [],
"obs_log": [],
"sen_log": [],
"hero_log": [],
"purchase_log": [],
"kills_log": [],
"buyback_log": [],
//removed for taking up too much space
//"pos": {},
"lane_pos": {},
"obs": {},
"sen": {},
//individual chat event counts?
//"CHAT_MESSAGE_HERO_KILL":{},
//"clicks":{},
"pings": {},
"purchase": {},
"gold_reasons": {},
"xp_reasons": {},
"kills": {},
"item_uses": {},
"ability_uses": {},
"hero_hits": {},
"damage": {},
"damage_taken": {},
"damage_inflictor": {},
"runes": {},
"killed_by": {},
"modifier_applied": {},
//"modifier_lost": {},
//"ability_trigger": {}
"kill_streaks": {},
"multi_kills": {},
"healing": {},
"hero_id": "", // the hero id of this player
"kill_streaks_log": [], // an array of kill streak values
// where each kill streak is an array of kills where
// where each kill is an object that contains
// - the hero id of the player who was killed
// - the multi kill id of this kill
// - the team fight id of this kill
// - the time of this kill
"multi_kill_id_vals": [] // an array of multi kill values (the length of each multi kill)
};
})
};
}
function generatePositionData(d, p) {
//d, a hash of keys to process
//p, a player containing keys with values as position hashes
//stores the resulting arrays in the keys of d
//64 is the offset of x and y values
//subtracting y from 127 inverts from bottom/left origin to top/left origin
for (var key in d) {
var t = [];
for (var x in p[key]) {
for (var y in p[key][x]) {
t.push({
x: Number(x) - 64,
y: 127 - (Number(y) - 64),
value: p[key][x][y]
});
}
}
d[key] = t;
}
return d;
}
function isSignificant(constants, m) {
return Boolean(constants.game_mode[m.game_mode] && constants.game_mode[m.game_mode].balanced && constants.lobby_type[m.lobby_type] && constants.lobby_type[m.lobby_type].balanced);
}
function reduceMatch(match) {
//returns only the minimum of data required for display
delete match.all_players;
delete match.parsed_data;
delete match.my_word_counts;
delete match.all_word_counts;
match.players.forEach(function(p) {
delete p.parsedPlayer;
});
return match;
}
function max(array) {
return Math.max.apply(null, array);
}
function min(array) {
return Math.min.apply(null, array);
}
function invokeInterval(func, delay) {
//invokes the function immediately, waits for callback, waits the delay, and then calls it again
(function foo() {
console.log("running %s", func.name);
func(function(err) {
if (err) {
//log the error, but wait until next interval to retry
console.log(err);
}
setTimeout(foo, delay);
});
})();
}
module.exports = {
tokenize: tokenize,
logger: logger,
generateJob: generateJob,
getData: getData,
convert32to64: convert32to64,
convert64to32: convert64to32,
isRadiant: isRadiant,
mergeObjects: mergeObjects,
mode: mode,
generatePositionData: generatePositionData,
getParseSchema: getParseSchema,
isSignificant: isSignificant,
reduceMatch: reduceMatch,
max: max,
min: min,
invokeInterval: invokeInterval
};