forked from jonbo/node-steam-webapi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
340 lines (270 loc) · 9.87 KB
/
index.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
// Dependencies
var http = require('http');
var https = require('https');
var querystring = require('qs');
/**
* Steam Class
*
* @param {Object} steamObj A default steamObj that will be referenced from every method call
* @constructor
*/
var Steam = function(steamObj) {
extend(this, steamObj);
};
// Expose module
module.exports = Steam;
// Popular game appIDs/gameIDs static references
Steam.TF2 = 440;
Steam.DOTA2 = 570;
Steam.PORTAL2 = 620;
Steam.CSGO = 730;
// References will be stored here
Steam.INTERFACES = {};
/**
* Retrieve the current set of Steam WebAPI methods from the API itself
*
* @param {String} (optional) key A Steam API key
* @param {Function} callback After the methods are retrieved and compiled for reference
*/
Steam.ready = function(key, callback) {
// If optional key was not given
if (typeof(key) === "function") {
callback = key;
key = undefined;
}
retrieveSteamAPIMethods(key, callback);
};
Steam.devMode = false;
// Create easy reference to the prototype
var steam = Steam.prototype;
// Global defaults
steam.secure = true;
steam.host = 'api.steampowered.com';
/**
* Helper function to make the HTTP request with a valid Steam WebAPI url
*
* @param {String} interfaceName
* @param {String} funcName
* @param {String|Number} version e.g. 1, "1", "v1", or "v0001"
* @param {Object} parameters
* @param {Function} callback The data returned by the request
*/
steam.request = function(interfaceName, funcName, version, httpMethod, parameters, callback) {
// Allow to be passed as a number or string
if (typeof(version) === 'number' || !isNaN(parseInt(version))) version = 'v'+version;
if (typeof(parameters) === 'object') {
// Change parameter object for service interfaces
// https://developer.valvesoftware.com/wiki/Steam_Web_API#Calling_Service_interfaces
if(interfaceName.toLowerCase().indexOf('service') > 0) {
var key = parameters.key,
format = parameters.format,
input = parameters;
delete input['key'];
delete input['format'];
parameters = {
key: key,
input_json: JSON.stringify(input)
};
if(format){
parameters.format = format;
}
}
parameters = querystring.stringify(parameters);
}
var options = {
method: httpMethod,
host : get(this, null, 'host'),
path : '/' + interfaceName + '/' + funcName + '/' + version
};
if (httpMethod === "GET") {
options.path += '/?' + parameters;
}
else if (httpMethod === "POST") {
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(parameters)
};
options.data = parameters;
}
request(this, options, callback);
};
/**
* Helper method to get a value by searching for it by priority
*
* First checking the options object passed in to the method call
* then the instance object properties
* or finally the global Steam object
*/
//
function get(self, steamObj, key) {
steamObj = steamObj || {};
if (steamObj[key] !== undefined) {
return steamObj[key];
}
else if (self[key] !== undefined) {
return self[key];
}
else if (Steam[key] !== undefined) {
return Steam[key];
}
else {
throw new Error("Missing required field: "+key);
}
}
// Handle the actual HTTP request
function request(self, options, callback) {
var _http = get(self, options, 'secure')? https : http;
if (Steam.devMode) console.log(options);
var req = _http.request(options, function(res) {
var data, dataStr = '';
res.on('data', function (chunk) {
dataStr += chunk;
});
res.on('end', function(){
var statusCode = res.statusCode;
if (statusCode !== 200) {
if (statusCode === 401) {
return callback(new Error('Invalid API Key'));
}
else {
return callback(new Error("HTTP "+statusCode+" "+http.STATUS_CODES[statusCode]));
}
}
// Ensure it is complete and valid JSON
try {
dataStr = dataStr.split('\n').pop();
data = JSON.parse(dataStr);
}
catch (e) {
return callback(new Error('Unable to parse JSON data'));
}
// Trim or simplify data object if it's entirely wrapped in data.response or data.result
if ((data.response instanceof Object) && (Object.keys(data).length === 1)) {
data = data.response;
}
if ((data.result instanceof Object) && Object.keys(data).length === 1) {
data = data.result;
}
callback(null, data);
})
});
req.end(options.data);
req.on('error', function(err) {
callback(err);
});
}
// Get the parameters from the steamObj passed in or Steam instance
function getParams(self, steamObj, requiredParams, optionalParams) {
// Required params will throw exception if they don't exist
var paramObj = {};
for (var i = 0, len = requiredParams.length; i < len; i++) {
var paramName = requiredParams[i];
// Support array arguments
paramName = paramName.replace("[0]","");
paramObj[paramName] = get(self, steamObj, paramName);
}
// Ignore the thrown exception on optionalParams if field isn't given
for (var i = 0, len = optionalParams.length; i < len; i++) {
var paramName = optionalParams[i];
// Support array arguments
paramName = paramName.replace("[0]","");
try {
paramObj[paramName] = get(self, steamObj, paramName);
} catch(e) {
}
}
return paramObj;
}
// Add some easy references to the new method
function addInterfaceMethod(interfaceName, funcName, fN) {
// Store a reference to every interface/method
if (Steam.INTERFACES[interfaceName] === undefined) {
Steam.INTERFACES[interfaceName] = {};
}
Steam.INTERFACES[interfaceName][funcName] = fN;
// Camel case the method name
var name = funcName.substr(0,1).toLowerCase() + funcName.substr(1);
// Add method to Steam's prototype
if (!isMultiGameInterface(interfaceName)) {
steam[name] = fN;
}
// If multiple interfaces use the same method name
// Create a new method that requires a gameid property to find the correct method
// and call the steam method automatically
else {
// We only need to do this once
if (steam[name] !== undefined) return;
// e.g. Turns 'IEconItems_440' into 'IEconItems'
var multi_interface_name = interfaceName.split('_')[0];
// Add method to Steam's prototype
steam[name] = function(steamObj, callback) {
var gameid = get(this, steamObj, 'gameid');
var interface_name = multi_interface_name + '_' + gameid;
Steam.INTERFACES[interface_name][funcName].call(this, steamObj, callback);
};
}
}
// Builds the method and add references
function buildSteamWrapperMethod(interfaceName, funcName, defaultVersion, httpMethod, requiredParams, optionalParams) {
// Always include the key and language fields, if available
// GetSupportedAPIList doesn't always list them.
optionalParams.push('key');
optionalParams.push('language');
// Require gameid for methods with the same name in the different interfaces
if (isMultiGameInterface(interfaceName)) {
requiredParams.push('gameid');
}
var wrapperMethod = function(steamObj, callback) {
var params = getParams(this, steamObj, requiredParams, optionalParams);
var version = steamObj.version || defaultVersion;
this.request(interfaceName, funcName, version, httpMethod, params, callback);
};
addInterfaceMethod(interfaceName, funcName, wrapperMethod);
}
// All we need to get started, we will build and attach the rest later (down below)
buildSteamWrapperMethod('ISteamWebAPIUtil', 'GetSupportedAPIList', 1, "GET", [], ['key']);
// Retrieve all Steam WebAPI http methods and add to our class prototype
function retrieveSteamAPIMethods(key, callback) {
var _steam = new Steam();
_steam.getSupportedAPIList({key:key}, function(err, data) {
if (err) return callback(err);
var apiList = data.apilist;
if (apiList === undefined) return callback(new Error('No data returned'));
apiList = apiList.interfaces;
// List of interfaces
for (var i= 0; i<apiList.length; i++) {
var _interface = apiList[i];
var methods = _interface.methods;
// List of methods
for (var j= 0; j<methods.length; j++) {
var method = methods[j];
var optionalParams = [], requiredParams = [];
var params = method.parameters;
//List of parameters
for (var k=0; k<params.length; k++) {
var param = params[k];
if (param.optional) {
optionalParams.push(param.name);
} else {
requiredParams.push(param.name);
}
}
buildSteamWrapperMethod(_interface.name, method.name, method.version, method.httpmethod, requiredParams, optionalParams);
}
}
callback();
});
}
// e.g IEconItems_440 -> true, ISteamNews -> false
function isMultiGameInterface(_interface) {
return _interface.indexOf('_') !== -1;
}
// Object extend
function extend(destination, source) {
for (var property in source) {
if (source.hasOwnProperty((property))) {
destination[property] = source[property];
}
}
return destination;
}